# -*-coding:utf-8-*-
from __future__ import absolute_import
import threading
from ..baidu_aip import AipContentCensor
import ctypes
import inspect
import _thread as threadvoicekeda
from time import mktime
from wsgiref.handlers import format_date_time
from urllib.parse import urlencode
import hmac
import ssl
import websocket
from collections import OrderedDict
import socket
import xmltodict
from queue import Queue
import http.client
from aliyunsdkcore.request import CommonRequest
from aliyunsdkcore.client import AcsClient

import base64
import hashlib
import os
import random
import re
from threading import Thread

import jieba
import jieba.analyse
import config
from chatterbot.zyrobot.decorators import time_statistic

from .intentionsql import *
from .phonesql import *
from ..conf import backtxt, baiduapp
from logging import getLogger

web_logger = getLogger('web_logger')
voice_logger = getLogger('voice_logger')

baiduapitoken = "24.4311672d54d4bc84596ae91dc2e12119.2592000.1553488921.282335-11325623"
backclose = (
    ['1', '空号,核对,有误,查证,不正确,不存在,过期,查正后'], ['2', '关机'], ['6', '停机,暂停服务'], ['17', '无人,无人接听'],
    ['3', '无法接通,无法接听,留言,发送,按一,来电,短信,提醒'], ['4', '欠费,交话费'],
    ['7', '正在,通话,挂机,不方便'], ['8', '正忙'],
    ['9', '呼入,限制,呼叫受限,越前使用,受限'],
    ['10', '未登记,国际长途'], ['11', '加0,加零,无需,直接,零'], ['13', '前加,拨长途,区号'], ['15', '网络'],
    ['16', '尚未,申请,此项,服务'], ['17', '接听,拨打,用户,号码,宁波,宁波打的,您拨,稍后,再拨'], ['1', 'checkthenumber,number,check'],
    ['7', 'youdialedisbusynow,tryagain'], ['8', 'busy,sorry'], ['4', 'repay'])

message = conn.j_message
java_ip = conn.w_java_ip
notcmpid = '无效的token！！或输入为空！！ '


def gr(cid, text, who, token, channelid, clevel, location, choiceback, dbname):
    web_logger.info('cid:%s text:%s token:%s' % (cid, text, token))
    # 返回公司编码
    cmpid = getcmpid(token, dbname, cid)
    # 判断公司编码是否有效
    if cmpid != '' and cmpid != conn.err and text != "":

        # 插入调用机器人记录并返回编码
        sessionid = insetCallrecords(cid, text, who, cmpid, channelid, clevel, location, dbname)

        # 判断插入是否成功
        if sessionid != 0 and sessionid != conn.err:
            # 判断是否开启api
            ifopenapi = judgeapiopen(cmpid, dbname, cid)
            if ifopenapi == 1:
                # 判断是否调用接口
                backurl = jugecallurl(cmpid, text, sessionid, dbname, cid)
                # 调用机器人
                if backurl == "":
                    return callrobot1(cmpid, text, sessionid, cid, choiceback, location, channelid, '-1', dbname)

                elif backurl == conn.err:
                    return backtypeadd(0, cid, 1, "调用第三放接口出错", '')
                else:  # 成功调用接口
                    backcon1 = backtypeadd(1, cid, 1, json.dumps(backurl, ensure_ascii=False), '')
                    sufins = insertbackrecord(sessionid, 1, 5, backcon1, dbname, cid)
                    if sufins == conn.err:
                        return backtypeadd(0, cid, 1, "插入调用接口错误！", '')
                    else:
                        return backcon1
            else:
                return callrobot1(cmpid, text, sessionid, cid, choiceback, location, channelid, '-1', dbname)

        else:
            return backtypeadd(0, cid, 1, "插入调用机器人错误！", '')

    else:
        return backtypeadd(0, cid, 1, notcmpid, '')


def selcmpid(serviceid, dbname, cid):
    sql = " SELECT r.cmpid from zt_cmp_robot r where r.onserviceid='" + str(serviceid) + "' "
    cmpid = conn.mysql_selrowid(sql, dbname, cid)
    return cmpid


def backquestion(code, backanswer):
    backtuple = {'code': str(code), 'backanswer': backanswer}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s' % backcon)
    return backcon


def sel_quesid_answers(questid, dbname, cid):
    sql = "SELECT answertype,answer,remark,qtype,quesid,type,content,voxfile from zt_know_answer where quesid='" + str(
        questid) + "'"
    back = conn.mysql_sel(sql, dbname, cid)
    return back


def insert_question_excel(question, quesid, content, serviceid, datatype, answer, dbname, cid):
    sql = "INSERT into zt_know_question_test(question,quesid,content,serviceid,type,answer) VALUES" \
          " ('" + str(question) + "','" + str(quesid) + "','" + str(content) + "','" + str(serviceid) + "','" + str(
              datatype) + "','" + str(answer) + "')"
    conn.mysql_insertid(sql, dbname, cid)


def delvariant(backtext):
    reg = r'\{[^{}]*\}'
    variantlist = re.findall(reg, backtext)

    for variant in variantlist:
        if variant.count('#') == 2:
            backtext = backtext.replace(variant, '')
    return backtext


def IMphone_thread_child(cmpid, question, serviceid, dbname, cid):
    if question != "":
        ans = mongorobot.getanwservicequestion(cmpid, question, "", serviceid, "", "", "", "", "", dbname)  # 查询到问题编码
        answertypedata = ()

        if ans[:1] == 'A':
            questid = str(ans[1:])
            answertypedata = sel_quesid_answers(
                questid, dbname, cid)  # 通过quesid查询到answertypedata中的 answertype,answer,remark,qtype,quesid,type,content
        if len(answertypedata) != 0:
            backtext = answertypedata[0][2]
            answertype = answertypedata[0][0]  # 先查询到answertype，取值为 1/2/3
            if answertypedata[0][3] == 2:  # 变量
                if answertype == 2:
                    backremark = delvariant(backtext)  # backvariant(backtext, "", answertypedata[0][3], cmpid, "")
                    if backremark == '@':
                        backremark = ''
                else:  # 如果answertype是1或者3

                    backtext = delvariant(answertypedata[0][1])  # backvariant(answertypedata[0][1], "", 1, cmpid, "")
                    backremark = backtext

            else:  # 非变量
                if answertype == 2:
                    backremark = backtext  # 如果是2的话就默认是remark
                else:
                    backremark = answertypedata[0][1]  # 如果是1或者3就是answer

            # type = robotsql.sel_question_test(answerid)     # 查询zt_know_answer中的type(question,quesid,content,serviceid,type,answer,voxfile)
            insert_question_excel(question, answertypedata[0][4],
                                  '' if answertypedata[0][6] is None else answertypedata[0][6], serviceid,
                                  '' if answertypedata[0][5] is None else answertypedata[0][5], backremark, dbname, cid)
        else:
            insert_question_excel(question, '', '', serviceid, '', '', dbname, cid)


thread = locals()


def IMphone_thread(cmpid, filetxt, serviceid, dbname, cid):
    try:
        count = 0

        for line in filetxt.readlines():
            question = line.decode('gbk').strip()

            thread['filetxt' + str(serviceid) + str(count)] = ThreadWithReturnValue(
                target=IMphone_thread_child,
                args=(cmpid, question, serviceid, dbname, cid))
            count = count + 1

        for count in range(count):
            thread['filetxt' + str(serviceid) + str(count)].start()
        for count in range(count):
            thread['filetxt' + str(serviceid) + str(count)].join()
        return 1
    except Exception as e:
        web_logger.error('cmpid:%s serviceid:%s error:%s %s', cmpid, serviceid, type(e), e)


def getHeader(API_KEY, APPID, auth_id, file):
    import time
    import hashlib
    import base64
    # x_time = int(int(round(time.time() * 1000)) / 1000)
    curTime = int(int(round(time.time() * 1000)) / 1000)

    param = {"aue": "raw", "auth_id": str(auth_id), "data_type": "audio", "sample_rate": "8000", "scene": "main"}

    x_param = base64.b64encode(json.dumps(param).replace(' ', '').encode('utf-8'))

    x_checksum_content = str(API_KEY) + str(curTime) + str(x_param, 'utf-8')

    x_checksum = hashlib.md5(x_checksum_content.encode('utf-8')).hexdigest()

    header = {
        'X-CurTime': str(curTime),
        'X-Param': x_param,
        'X-Appid': str(APPID),
        'X-CheckSum': x_checksum,
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'User-Agent': 'User-Agent:Mozilla/5.0',
        # 'User-Agent': 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
    }
    voice_logger.info(
        "header:%s file:%s API_KEY:%s auth_id:%s x_checksum_content:%s curTime:%s " % (
            header, str(file), API_KEY, auth_id, x_checksum_content, curTime)
    )

    return header


def getBody(filepath):
    binfile = open(filepath, 'rb')
    try:
        data = binfile.read()
        # print(type(data),'data')
        return data
    except:
        return ''
    finally:
        binfile.close()


def getaliyuntoken(keyid, keysecret):
    voice_logger.info('keyid:%s keysecret:%s' % (keyid, keysecret))
    try:
        # print('ddd')
        # 创建AcsClient实例
        # appKey = '4vWLkbHz0yK8sBxH'
        # client = AcsClient(
        #    "LTAI9ae2VFpE2o83",#key-id
        #    "gKGz1nFEEvWCkpSFNFX1rRWKoOcUhz",#key-secret钟展
        #    "cn-shanghai"
        # )
        client = AcsClient(
            str(keyid),  # keyid
            str(keysecret),  # keysecret
            "cn-shanghai"
        )
        # 创建request，并设置参数
        request = CommonRequest()
        request.set_method('POST')
        request.set_domain('nls-meta.cn-shanghai.aliyuncs.com')
        request.set_version('2018-05-18')
        request.set_uri_pattern("/pop/2018-05-18/tokens")
        response = client.do_action_with_exception(request)
        data = response.decode("utf-8")
        request.keep_alive = False
        voice_logger.info('data:%s' % data)
        d = json.loads(data)

        return str(d['Token']['Id'])
    except Exception as e:
        voice_logger.error('error:%s %s', type(e), e)
        return ''


def get_vocie_stream(file):
    # pass
    try:
        url = "http://" + str(conn.vocie_stream_url) + "/audio_stream?file=" + str(file)
        req = rs.get(url, timeout=4)
        data = req.content
        return data
    except Exception as e:
        voice_logger.error('error:%s %s', type(e), e)
        return ''


# 调用阿里云翻译接口
def getaliyunurl(file, appKey, token, choose):
    try:  # nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/asr
        request = "http://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/asr?appkey=" + appKey + '&format=pcm' + '&sample_rate=8000' \
                  + "&enable_punctuation_prediction=false" + "&enable_inverse_text_normalization=false" + "&enable_voice_detection=" + choose + ""
        audioContent = getBody(file)
        voice_logger.info('url:%s choose:%s', request, choose)
        if audioContent:
            host = 'nls-gateway.cn-shanghai.aliyuncs.com'
            # 设置HTTP请求头部
            httpHeaders = {
                'X-NLS-Token': token,
                'Content-type': 'application/octet-stream',
                'Content-Length': len(audioContent)
            }
            conn = http.client.HTTPConnection(host, timeout=4)
            conn.request(method='POST', url=request, body=audioContent, headers=httpHeaders)
            response = conn.getresponse()
            body = response.read().decode("utf-8")
            voice_logger.info('body:%s file:%s appKey:%s choose:%s' % (body, file, appKey, choose))
            conn.close()
            return body
        voice_logger.info('文件为空或找不到文件 file_path:%s' % (file))
        return json.dumps({"task_id": "文件为空或找不到文件", "result": "", "status": 20000000, "message": "SUCCESS"},
                          ensure_ascii=False, sort_keys=True)

    except Exception as e:
        if str(e) != 'timed out':
            voice_logger.error('file:%s appKey:%s error:%s %s', file, appKey, type(e), e)
        voice_logger.error('调用阿里云超时 file:%s error:%s %s', file, type(e), e)

        return json.dumps({"task_id": "异常输出，可能超时", "result": "", "status": 20000000, "message": "SUCCESS"},
                          ensure_ascii=False, sort_keys=True)


def getaliyunurl_tong(url, appKey, devKey, file):
    try:
        # wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1
        # http://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/asr
        # curTime = int(int(round(time.time() * 1000)) / 1000)
        time_data = time.strftime("%Y-%m-%d %H:%M:%S")
        x_session_key = str(time_data) + str(devKey)

        x_session_key = hashlib.md5(x_session_key.encode('utf-8')).hexdigest()

        host = url
        request = "http://" + str(url) + "/asr/Recognise"
        voice_logger.info('url:%s appKey%s devKey:%s file:%s appKey:%s', request, appKey, devKey, file)
        # # 设置HTTP请求头部
        httpHeaders = {
            'x-app-key': str(appKey),
            'x-sdk-version': '5.0',
            'x-request-date': str(time_data),
            'x-result-format': 'json',
            'x-session-key': x_session_key,
            'x-udid': '101:1234567890',
            'x-task-config': str("capkey=asr.cloud.freetalk,audioformat=pcm8k16bit,domain=telecom"),
        }
        audioContent = getBody(file)
        conn = http.client.HTTPConnection(host, timeout=10)

        conn.request(method='POST', url=request, body=audioContent, headers=httpHeaders)
        response = conn.getresponse()
        body = response.read().decode("utf-8")
        voice_logger.info('body:%s file:%s appKey:%s', body, file, appKey)
        conn.close()
        return body
    except Exception as e:
        web_logger.error('file:%s appKey:%s error:%s %s', file, appKey, type(e), e)
        return ''


aliyundata = conn.a_aliyundata


aliyundatakou = [

    {'appKey': 'jSf4MZpFzzKSW1ww', 'keyid': 'LTAI5Vz3cU71J93J',
        'keysecret': 'Koqk8ExIUJREclyzGC7J8Dz1Ljylkg', 'token': '9440f6b4811543b4af9ef2eac56873bes'},  # 公司口音
    {'appKey': 'c2sj72UBJlmoq1bW', 'keyid': 'LTAI9ae2VFpE2o83',
        'keysecret': 'gKGz1nFEEvWCkpSFNFX1rRWKoOcUhz', 'token': '9671bbdfaa2e455d952e6a7c4b838d91'},  # 钟展
    {'appKey': 'PjJmARF4qpvVOJvh', 'keyid': 'LTAIMWfSZPZ02Sam',
        'keysecret': 'G42OflYeoPw09od9qx49U4J73DqGxw', 'token': 'd4422acba53344539b617b51740c3c3f2'},  # lzj
    {'appKey': 'iUSlnRkizhyFvEVc', 'keyid': 'LTAIF1uG0jn0XG6E',
        'keysecret': 'brwGZ16CMVdi8PT8QGh774009QKCTh', 'token': 'c87ffd5de5954e3ca4188befd8fba8f53'},  # 姚
    {'appKey': 'W5S3Eb752A5qa8TU', 'keyid': 'LTAITErAEoTGaLFJ',
        'keysecret': '3vkbMDMVTQNY8T34dHUmorkoMfimi7', 'token': '05381a5b87954fa38450f6d5d9272f8f'},  # 涛
    {'appKey': 'XyGHqE53cXWJfLr7', 'keyid': 'LTAIjV5rvFlJSV09',
        'keysecret': '6EMqasThymutU5eUGeUAyMf4SWNUu6', 'token': '3fb5018b31e541e8b09055d45ea3fc4c7'},  # 高

    {'appKey': 'as0GcNpFVeb6Ba98', 'keyid': 'LTAIfm1CkQjMsiMd',
        'keysecret': 'V1qrc8hig9b9dnruLFwSnjZjTvcmM7', 'token': 'af4a1b24f1dd4eb6bb044406df25aabfs'},  # 松
    {'appKey': 'S6Wtgpu0iEI1jqwm', 'keyid': 'LTAIffftRvUK84XP',
        'keysecret': 'KEYjC9BlKbo8pGPTIDfeaRvH12VfXi', 'token': '9440f6b4811543b4af9ef2eac56873bes'},  # 冰箱
    # {'appKey':'SFSmQQCrYkOCHveU','keyid':'LTAIQGRwDl6HXXxE','keysecret':'HVlUSUvMtKjeiukKJh9gmWQiAziBZN'
    #     ,'token':'9440f6b4811543b4af9ef2eac56873bes'},#小黄
    {'appKey': 'Kj3wdG1lDjJx2cjk', 'keyid': 'LTAIyxb4ieaf9XLv',
        'keysecret': 'YgMyNq8VFJik4Ek73NsGoTMk8wgWom', 'token': 'fd4bfcbbb445445d835edd7b83283547'},  # 小胡
    {'appKey': 'mUkl7h2NZNtfz8Ku', 'keyid': 'LTAIj4dPDdlhUgFA',
        'keysecret': 'gdWClN2EzE35d9oetAUoSmfp6vwbn6', 'token': '06a4c23c821f4360803d95182cb07d71'},  # 科特
    {'appKey': 'euNAOCnDFCv8puf7', 'keyid': 'LTAIucSOg52UbiCs',
        'keysecret': 'fuo7fJDV69Iy3iL8RIcTb4nRrhsY91', 'token': 'f37b01826d854d1da479c740c237bd31'},  # 苗苗
    # {'appKey': 'B95Uxjn4B5yTr1Jl', 'keyid':'LTAI4GATRfpJkkMhevi9yiKF', 'keysecret': 'p2nTUdb0ERQXGKiZbuRtaPMFe93sZC', 'token': ''},#地产本地部署
]

aliyundatayueyu = [

    {'appKey': 'TaA9rsxgbS5vOnYJ', 'keyid': 'LTAI5Vz3cU71J93J',
        'keysecret': 'Koqk8ExIUJREclyzGC7J8Dz1Ljylkg', 'token': '9440f6b4811543b4af9ef2eac56873bes'},  # 公司粤语
    {'appKey': '2lRQJqw91iobaWmI', 'keyid': 'LTAI9ae2VFpE2o83',
        'keysecret': 'gKGz1nFEEvWCkpSFNFX1rRWKoOcUhz', 'token': '9671bbdfaa2e455d952e6a7c4b838d91'},  # 钟展
    {'appKey': 'iUiyDyyuFLwWka43', 'keyid': 'LTAIMWfSZPZ02Sam',
        'keysecret': 'G42OflYeoPw09od9qx49U4J73DqGxw', 'token': 'd4422acba53344539b617b51740c3c3f2'},  # lzj
    {'appKey': 'Gz6NCmKht7EG86vR', 'keyid': 'LTAIF1uG0jn0XG6E',
        'keysecret': 'brwGZ16CMVdi8PT8QGh774009QKCTh', 'token': 'c87ffd5de5954e3ca4188befd8fba8f53'},  # 姚
    {'appKey': 'BnrM0O9uzWWzFl07', 'keyid': 'LTAITErAEoTGaLFJ',
        'keysecret': '3vkbMDMVTQNY8T34dHUmorkoMfimi7', 'token': '05381a5b87954fa38450f6d5d9272f8f'},  # 涛
    {'appKey': '2DFalOPbxhiQoJA4', 'keyid': 'LTAIjV5rvFlJSV09',
        'keysecret': '6EMqasThymutU5eUGeUAyMf4SWNUu6', 'token': '3fb5018b31e541e8b09055d45ea3fc4c7'},  # 高

    {'appKey': '6lKCubJIZDNpfiyd', 'keyid': 'LTAIfm1CkQjMsiMd',
        'keysecret': 'V1qrc8hig9b9dnruLFwSnjZjTvcmM7', 'token': 'af4a1b24f1dd4eb6bb044406df25aabfs'},  # 松
    {'appKey': 'ryL2KGhpb49z1T2d', 'keyid': 'LTAIffftRvUK84XP',
        'keysecret': 'KEYjC9BlKbo8pGPTIDfeaRvH12VfXi', 'token': '9440f6b4811543b4af9ef2eac56873bes'},  # 冰箱
    # {'appKey':'SFSmQQCrYkOCHveU','keyid':'LTAIQGRwDl6HXXxE','keysecret':'HVlUSUvMtKjeiukKJh9gmWQiAziBZN'
    #     ,'token':'9440f6b4811543b4af9ef2eac56873bes'},#小黄
    {'appKey': 'ceymzMdMAFCqA0Xu', 'keyid': 'LTAIyxb4ieaf9XLv',
        'keysecret': 'YgMyNq8VFJik4Ek73NsGoTMk8wgWom', 'token': 'fd4bfcbbb445445d835edd7b83283547'},  # 小胡
    {'appKey': '952YoDbvHPMHU4ll', 'keyid': 'LTAIj4dPDdlhUgFA',
        'keysecret': 'gdWClN2EzE35d9oetAUoSmfp6vwbn6', 'token': '06a4c23c821f4360803d95182cb07d71'},  # 科特
    {'appKey': 'Ynj6YhGRpyFwX1ze', 'keyid': 'LTAIucSOg52UbiCs',
        'keysecret': 'fuo7fJDV69Iy3iL8RIcTb4nRrhsY91', 'token': 'f37b01826d854d1da479c740c237bd31'},  # 苗苗
    # {'appKey': 'B95Uxjn4B5yTr1Jl', 'keyid':'LTAI4GATRfpJkkMhevi9yiKF', 'keysecret': 'p2nTUdb0ERQXGKiZbuRtaPMFe93sZC', 'token': ''},#地产本地部署
]


aliyunqueue = Queue(maxsize=0)
aliyunallnum = len(aliyundata)
for i in range(aliyunallnum * 2):
    # 写入队列数据
    aliyunqueue.put(i)

# 方言
aliyunqueuefanyan = Queue(maxsize=0)
aliyunfanyanallnum = len(aliyundatakou)
for i in range(aliyunfanyanallnum):
    # 写入队列数据
    aliyunqueuefanyan.put(i)

# 粤语
aliyunqueueyueyu = Queue(maxsize=0)
aliyunyueyuallnum = len(aliyundatayueyu)
for i in range(aliyunyueyuallnum):
    # 写入队列数据
    aliyunqueueyueyu.put(i)


# 阿里云翻译错误处理流程
def processaliyun(file, industryid):
    data = 0
    queuedata = 0
    try:
        queuedata = int(aliyunqueue.get(timeout=2))
        if queuedata >= aliyunallnum:
            data = queuedata - aliyunallnum
        else:
            data = queuedata
        # data = 1
        appKey = aliyundata[data]["appKey"]
        keyid = aliyundata[data]["keyid"]
        keysecret = aliyundata[data]["keysecret"]
        token = aliyundata[data]["token"]

        voice_logger.info('file:%s data:%s queuedata:%s', file, data, queuedata)
        voice_logger.debug('aliyunqueue:%s', aliyunqueue.queue)

        bodyjson = getaliyunurl(file, appKey, token, 'false')  # false
        voice_logger.info('bodyjson:%s' % bodyjson)

        aliyunqueue.put(queuedata)
        if bodyjson == '':
            voice_logger.warning('翻译问题 bodyjson:%s' % bodyjson)
            return ''
        bodyjson = json.loads(bodyjson)

        if bodyjson["status"] == 20000000:
            return bodyjson["result"]

        elif bodyjson["status"] == 40000001:
            newtoken = getaliyuntoken(keyid, keysecret)
            token = newtoken
            aliyundata[data]["token"] = newtoken
            bodyjson = getaliyunurl(file, appKey, token, 'false')
            bodyjson = json.loads(bodyjson)
            return bodyjson["result"]
        elif bodyjson["status"] == 40010005:
            return ''
        elif bodyjson["status"] == 40000000:
            return ''
        elif bodyjson["status"] == 40000005:
            return processaliyun(file, industryid)
        else:
            weixin_push(str(keyid), str(bodyjson), "翻译出错！！")
            web_logger.warning('bodyjson:%s file:%s appKey:%s', bodyjson, file, appKey)
            return ''
    except Exception as e:
        if str(queuedata) != '0':
            aliyunqueue.put(queuedata)
        weixin_push(str(file), str(e), "翻译出错！！")
        web_logger.error('file:%s  error:%s %s', file, type(e), e)
        return ''


def processatong(file):
    # 阿里和捷通之间的互换
    try:
        appKey = 'ac5d5452'
        devkey = 'developer_key'

        # url = 'api.hcicloud.com:8880'
        url = '10.0.1.192:8880'

        bodyjson = getaliyunurl_tong(url, appKey, devkey, file)
        # bodyjson = json.loads(bodyjson)
        bodyjson = json.loads(json.dumps(xmltodict.parse(bodyjson), ensure_ascii=False))

        if bodyjson['ResponseInfo']["ResCode"] == 'Success':
            return bodyjson['ResponseInfo']["Result"]['Text']
        else:
            weixin_push('捷通', '错误', "翻译出错！！")
            voice_logger.error('file:%s' % file)
        return ''

    except Exception as e:
        weixin_push('捷通', str(e), "翻译出错！！")
        voice_logger.error('file:%s error:%s %s', file, type(e), e)
        return ''


ip = socket.gethostbyname(socket.gethostname())


def weixin_push(remark, content, title):
    # pass
    try:
        url = "http://" + str(java_ip) + "/wx_api2/rest/?action=sendEarlyWarningMessage&title='" + str(
            title + ip) + "'&remark='" + str(remark) + "'&content='" + str(content) + "'&userid=10735"  # 2319
        # print(url) #1963程涛  2386兆娟
        req = rs.post(url, timeout=2)
        # print(req)
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)


def weixin_push_userid(remark, content, title, userid):
    # pass
    try:
        url = "http://" + str(java_ip) + "/wx_api2/rest/?action=sendEarlyWarningMessage&title='" + str(
            title) + "'&remark='" + str(remark) + "'&content='" + str(content) + "'&userid='" + str(userid) + "'"
        # print(url) #1963程涛  2386兆娟
        req = rs.post(url, timeout=2)
        # print(req)
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)


# weixin_push("你是不是涛哥啊", "你是不是涛哥啊","你是不是涛哥啊")

# industryidalldata = {"industryid0":  # 默认
#     [
#         # {"appkey":"13adbccdd4d340f8b50949e81f55f43d","appid":"5aff8cde","authid":"edabe685281685c07b0c5ca5464cc5b3"},
#         #  {"appkey":"a3cdf3a98bf2462587e5d9545115d232","appid":"5b67a622","authid":"8ba27b5254698b2de4ad115bc2870f64"},
#         #  {"appkey":"fe9a4e6a5849402481037ac633a2802e","appid":"5b67a65c","authid":"b40d6e79e3f04be88173fd14899f81bf"},
#         # {"appkey":"4eb6e50e83a44c539e7aed073c3b3a03","appid":"5b67a689","authid":"b2a64950afced3db15ae5b3c50c030a2"},
#         # {"appkey":"74bec42a0201455da415421414f90f17","appid":"5b67a6b5","authid":"14d4c8c8d9c5ce88306262328245eab4"},
#         # {"appkey":"7121f1a2e1c64e0db007bcd33f9b9fd8","appid":"5b67a6dd","authid":"04a88f2d517cde49a5e38ed2fb918d32"},
#         #
#         # {"appkey":"7302748c45df468fb1cd5df733d1c264","appid":"5b68081e","authid":"c72c637de8516eea51e24678f3bcae50"},
#         # {"appkey":"e1b2d2bd93a34573afae6d91e823c301","appid":"5b68f1b5","authid":"2299ebc97effed900c98536f0b5daf5d"},
#         #  {"appkey":"c1d9c72000bb4e088e267d5bfe932650","appid":"5b68ff77","authid":"2c26a625cc8939634c4acca1b83a2f8d"},
#         # {"appkey":"8d886d74b26449b99355c2b02008cdd8","appid":"5b690f15","authid":"50f377a25252f1ea791bf53fb9be479b"},
#         {"appkey": "a4d530eb59b2f577143f8baab87e2eb0", "appid": "5cd53efd",
#          "authid": "07db062bacd8ee5dfd1cd542189cc61c"},  # 四川方言
#         # {"appkey":"54226286d966cc416705c499a17f6513","appid":"5c2349bc","authid":"6f568dfb82acf869fc2903d030dc2341"},
#         # {"appkey":"c486e734db9acacea183504ebd74ed57","appid":"5c234d32","authid":"8a079096d7d59b8c6c5b892cc4fa5a75"},
#         # {"appkey":"067fc430da64b231f0945f20d60cee26","appid":"5c234e2d","authid":"bc757adb41ee799b166ed5a303c934dd"},
#
#         # {"appkey":"c86084a9db3a9c8304e632fb323af64f","appid":"5c247fcd","authid":"e2902358d76eed47f081832f6ec5cdb6"},
#
#     ],
#     "industryid1":  # 房产
#         [
#             {"appkey": "5428fd1c43b545a7be4fc24e8d7a910d", "appid": "5b11007b",
#              "authid": "1501235dcc4c0683eb2a23c49102bfe1"},
#             {"appkey": "b2078b217f9c43c8979ab533d9a747ad", "appid": "5b641b5e",
#              "authid": "226c022a1a7a1281dacfd7d1a5943342"},
#             {"appkey": "85b9aa4a6c144cd9a08bfff15a460c6b", "appid": "5b641bff",
#              "authid": "a4a7ef55ceb7f01d74573f693ce4c949"},
#             {"appkey": "e26ef68ed6414614a4e050ce330f5aee", "appid": "5b641c66",
#              "authid": "9938aa208a523832a8bcfd51e8489fca"},
#             {"appkey": "1336d9c21ec44feaa14daf828a3b6a01", "appid": "5b641cc4",
#              "authid": "c360f918a318f18b1ca72278853c5004"},
#             {"appkey": "98649d476bcf4d32adc51509c927ebc4", "appid": "5b641d24",
#              "authid": "43612e0d6c5df74576284df6cc232a52"},
#
#             {"appkey": "c0797291bb5e4b11a0c2937db858ab1f", "appid": "5b681398",
#              "authid": "91ceb5048aa9654ebc5417de6b4e8c5f"},
#             {"appkey": "877378109ed24ee4afb0fec5f2dfcfa0", "appid": "5b68f2c6",
#              "authid": "4a5814648f7cd42bcd7b2abe2ef1eccd"},
#             {"appkey": "c957dc19318844fd8fc8097db810059c", "appid": "5b690029",
#              "authid": "f9dddb4019d7de0b8b0c82f0856cb13e"},
#             {"appkey": "a79b10e8294743539ac5b2f7b7c7a863", "appid": "5b690fe1",
#              "authid": "c55459c85f3efc6dd9318c80df1c301e"},
#
#             # {"appkey":"96d2ec9225284f5a695c5cb9231b5931","appid":"5c234ee5","authid":"a5dabc1b57dfe123607aee76835fb2a6"},
#             # {"appkey":"947ba708fdcadf1f816a439617043fdb","appid":"5c234f30","authid":"ae6586a6989bd58034a5f30c0c2da17c"},
#             # {"appkey":"76b9412f2d71f1f795fd40e8551dc4f0","appid":"5c234f7b","authid":"9d4b4918c16026263929f47a7b286027"},
#
#             # {"appkey":"cdf39596ce1a0f9c70bade502133af8d","appid":"5c248069","authid":"21ebdc594e9220c8b52c39319b0efa92"},
#         ],
#     "industryid2":  # 贷款
#         [
#             {"appkey": "07703d0f023746bebb4f69cc3c99653e", "appid": "5b11009c",
#              "authid": "5718045292889b8bb4cd91a23ce8579a"},
#             {"appkey": "ffb871136def4d5eba39d205479303e0", "appid": "5b641d89",
#              "authid": "15940d1cbbccfd3661040fb553ab3278"},
#             {"appkey": "c33645095b5048239c703265163c0c02", "appid": "5b641dca",
#              "authid": "feae399e3870e5b46bcb36688c10d599"},
#             {"appkey": "1c8d1d180c2445d186fe1ae32f40bb2c", "appid": "5b641e5e",
#              "authid": "2ead4350edc628368a4475fdcfbb4b1b"},
#             {"appkey": "219ef09f5552435b8fd69e1996c978c9", "appid": "5b641ec2",
#              "authid": "35e5c478dcde514d9c037f4da2dcbc59"},
#             {"appkey": "a6bc55c77bd44e0fa83b39de62a52ee4", "appid": "5b641efd",
#              "authid": "59c2f9276366dbfa4356b72941a0f7d2"},
#
#             {"appkey": "e4d3aefb8c124ed7a91fb395d4f7aae6", "appid": "5b0b5a2d",
#              "authid": "5676de169d2159f35311ceeac6a7247b"},
#             {"appkey": "b67ddaae82a64161b2104ca7488a1248", "appid": "5b68f319",
#              "authid": "e21bf973dccbc966e7b741931997f3d4"},
#             {"appkey": "0275f8a46bee412e97e77a9e36d61e05", "appid": "5b69005f",
#              "authid": "607f4f6443cf1b68cabf83f593289832"},
#             {"appkey": "95dc469fa63b497293312076e68a6877", "appid": "5b69102c",
#              "authid": "5497a8812e1772c7d3068d35fca47131"},
#
#             # {"appkey":"f88798bb19deeae81f2b664b2f2bb687","appid":"5c235003","authid":"b7eed4391dd00fc046abadb1cb689ebc"},
#             # {"appkey":"e6e1a047adb6142e1dc41c436b3d4ca2","appid":"5c235040","authid":"dc5de2310ec23dd1d14868103268cd0a"},
#             # {"appkey":"95a5992ea0c39b5873e27918344a9372","appid":"5c23506f","authid":"1666159805c8f5ff34305a45df3e3550"},
#
#             # {"appkey":"1fa2f926de7ad4ab96697f55a8cd3058","appid":"5c24810c","authid":"60d7d45288da48a21967d2be6c5d0bf5"},
#
#         ],
#     "industryid3":  # 保险
#         [
#             {"appkey": "7412ea52108a44cebdabd31e1ed4a8fa", "appid": "5b1100ca",
#              "authid": "d12dfb5267950dc702b6f2c3d0a9e648"},
#             {"appkey": "15641080e4d14e1c8742806af58aa8a0", "appid": "5b641fac",
#              "authid": "7d495bc500f41eb6dfd3570495aa59f5"},
#             {"appkey": "2dee656db445432b9756e003eee6f5a8", "appid": "5b641fdc",
#              "authid": "68d935bed86643a51fe50b62b0f24794"},
#             {"appkey": "bee468a06df847f7ba69f8373c9a7fe2", "appid": "5b64200f",
#              "authid": "bd5cebf5680a6463bbb7fb9ee6e3b761"},
#             {"appkey": "5c1b2ac1a52c4f768cc36e10be6a51a2", "appid": "5b64203c",
#              "authid": "73d79fe48bbcce3a46852b974936f083"},
#             {"appkey": "d10dd7481ce84f459326181a79ba1df6", "appid": "5b64206b",
#              "authid": "683d41ce4d8efa6ac754c01b014846bd"},
#
#             {"appkey": "a7f48788e83a428caf07ea6f16490066", "appid": "5b681601",
#              "authid": "362bf367d7d38f30e764d5e7cb499992"},
#             {"appkey": "a4e40776882b4930a5eac506a720fe17", "appid": "5b68f366",
#              "authid": "d78218acd7988470eed2484c804e91f5"},
#             {"appkey": "3ace0224c63a4c97becf0af3c92f0274", "appid": "5b69013d",
#              "authid": "947ccad3cbf303ee218e64e3005e8c18"},
#             {"appkey": "575679e65c564ef0873a27494e881ddf", "appid": "5b691074",
#              "authid": "9c24a2d3b19aeaaeafc6bee39e13843e"},
#
#             # {"appkey":"43d5fe93e22ff2a3af458b1043b0c48c","appid":"5c2350a6","authid":"8ca1521ce4f016a7a457fd7577cb4f51"},
#             # {"appkey":"6efe25a31d8a91ab0c3b01729baeb105","appid":"5c23511c","authid":"b9b7a88368ad7ca8fd58e1ea17830e87"},
#             # {"appkey":"01ea05013cf172acbbd08a4643bebdf4","appid":"5c235183","authid":"9c24a2d3b19aeaaeafc6bee39e13843e"},
#
#             # {"appkey":"d82bdce6a8548e33299cb7e5afd19fc4","appid":"5c248180","authid":"bb307937941711b13d150af0c0287d3b"},
#
#         ],
#     "industryid4":  # 催收
#         [
#             {"appkey": "13adbccdd4d340f8b50949e81f55f43d", "appid": "5aff8cde",
#              "authid": "edabe685281685c07b0c5ca5464cc5b3"},
#             {"appkey": "74089f6200c7449b940c463a5d3a08fc", "appid": "5b642143",
#              "authid": "55a510934803d04a74daae8b02325457"},
#             {"appkey": "0e9dbeaa1aeb42919402b6e1a99b6ae1", "appid": "5b642176",
#              "authid": "ad5a2cf23efab8bc68ed018f3a3bd5f6"},
#             {"appkey": "3b4886c74b784692b45212526eec9919", "appid": "5b6421c3",
#              "authid": "24890418c5e696a82688951974f71a73"},
#             {"appkey": "c7c9241437eb418097abc8e9cd1b583a", "appid": "5b6421f1",
#              "authid": "82d8fad892cfce6a2fc244d8750fb908"},
#             {"appkey": "5423cd9698c74bae91856d1efe3c2e8a", "appid": "5b64221e",
#              "authid": "a35fca945b9caeab5dadf526ded4d6fd"},
#
#             # {"appkey":"93d2f5eab8344417a66a2c5c000cc9b1","appid":"5b681681","authid":"f8bfa9a566e2237c2d7469df117f60f4"},
#             # {"appkey":"dc8a7a46cb3e4f38a572f71cd9f28298","appid":"5b68f3a7","authid":"37022effef10745e2513371b89157887"},
#             # {"appkey":"51aabb7e91e2440086b43fd430fae86b","appid":"5b69017b","authid":"8100d93464187a4196b818e676084221"},
#             # {"appkey":"72394ba0bd694361ae18a73161116334","appid":"5b6910b5","authid":"2b6e37bc56d42faaaf836361f723e24a"},
#
#             # {"appkey":"b97533849ea4caceddad27ba9f4f05fe","appid":"5c2481c4","authid":"e7499d0b27ac71f4718c797605a2c0fc"},
#         ],
#     "industryid5":  # 股票
#         [
#             {"appkey": "156407847f2842f882ddb65c2df41bde", "appid": "5b1100e8",
#              "authid": "76cec7d7e7e352fcfc790c16e687cd8e"},
#             {"appkey": "f120295fe01845139eb6e60bca1c131e", "appid": "5b642324",
#              "authid": "e5636f7f6d79637e9773376465e1a89b"},
#             {"appkey": "0c6fbece7a094ceab155446c6afb6024", "appid": "5b64234f",
#              "authid": "3a2ec268550ee19ecbd48ddf065b9752"},
#             {"appkey": "12d0fb72aff04dee97cc1ea90e42961a", "appid": "5b64237a",
#              "authid": "1f2c5c33f541d6cdbd7f06226ad617d9"},
#             {"appkey": "07baee9096b84b7889fe0353ccecbb0e", "appid": "5b6423a5",
#              "authid": "e23f98dc8d328f065711a1f55d549c45"},
#             {"appkey": "8aabc5c6db02489781e032a58255a66e", "appid": "5b6423d5",
#              "authid": "da2907b5f581f6c5737b41a9a40e7dd7"},
#
#             # {"appkey":"af38c6e33ece4837bbffe5128634c19e","appid":"5b6816cf","authid":"e75692a87a1af6f4a2980bb361bfcd4a"},
#             # {"appkey":"a7330ca4f19948dea1742aebf5c53be2","appid":"5b68f3f7","authid":"4b5342ee8f7dee254d6c9f1b603883bb"},
#             # {"appkey":"947b0114b8e14a07b987eb23868941ec","appid":"5b6901b7","authid":"f805d4e0cf06328bedddebada2ee6416"},
#             # {"appkey":"a5910a5e1f2046d2ba83a6c75048cf4c","appid":"5b6910fc","authid":"294f0e083c172269e8387f63b1138197"},
#         ],
#     "industryid6":  # 电商
#         [
#             {"appkey": "5bca2eaa3eeb4d7d81ddb8d0a1c1aac6", "appid": "5b1100fa",
#              "authid": "7c24816dec70f18d1c4b6549fea78306"},
#             {"appkey": "a14d1db1a3464283a8950be5eeac5c01", "appid": "5b6424ee",
#              "authid": "477622902e05063378dd784af43d00d5"},
#             {"appkey": "974b766dd2f24335b5a67cad03160dae", "appid": "5b64251b",
#              "authid": "31a58f6d5c3d77996fa3b97fcf956a69"},
#             {"appkey": "8e4acfe5dd9c4a48b7d579d785591890", "appid": "5b642551",
#              "authid": "6dc2804509e9d27f5fb81634c7ace4d2"},
#             {"appkey": "581386cc8a4b40e7a3eeffc52ac783ab", "appid": "5b642583",
#              "authid": "3e1c76ca3953024fad2b9dc71794da4b"},
#             {"appkey": "546bcb44d06f46b7bc39415ea8facc87", "appid": "5b6425ae",
#              "authid": "dd895a5acfb77069f28f3c62dd37178d"},
#
#             # {"appkey":"bbf9b710fd774821aa9cfc217163bd7f","appid":"5b68173d","authid":"bbe693195e437d6c4f5108eb76de7523"},
#             # {"appkey":"67b44d50db974fa7a299805fb1663689","appid":"5b68f448","authid":"b99f12da2a7ae46fcf3a96034ee6fe8c"},
#             # {"appkey":"5d29911b523342839f6256eca36ba582","appid":"5b6901f7","authid":"e348b5f5be1ad0623689fffce8e1c7bb"},
#             # {"appkey":"e22e31c86c92452ea942ae88a8715d31","appid":"5b691141","authid":"b3f2a0155949a2831a8ee8f8fbe6ce22"},
#         ],
#     "industryid7":  # 其他
#         [
#             {"appkey": "13adbccdd4d340f8b50949e81f55f43d", "appid": "5aff8cde",
#              "authid": "edabe685281685c07b0c5ca5464cc5b3"},
#             {"appkey": "d5b1381b223e4cd0908f9ba20a2542fa", "appid": "5b642670",
#              "authid": "086c7ba6d431d7f2eda7102787cdf745"},
#             {"appkey": "58560a077479477b9db08933d22de528", "appid": "5b6426a3",
#              "authid": "eeb8a79a8953cb6359efd84cfb6352d6"},
#             {"appkey": "c3939e8db936481890d3cd3081b0265d", "appid": "5b6426ce",
#              "authid": "d4ef53145f5a66c4acac9a32429cbf26"},
#             {"appkey": "55535f9dac1b482990d171fa05456c72", "appid": "5b6426fa",
#              "authid": "0184331ecfea70851a22de655a953c45"},
#             {"appkey": "ca9b7b2d56f84f7d9e53129db9188f0b", "appid": "5b642722",
#              "authid": "184793ec79c7e047d157c691b9ade92b"},
#
#             # {"appkey":"92f0422edcc0458488e78f54562f7db5","appid":"5b6817a8","authid":"9d0f000d4c60d9b4fec73418ab349b23"},
#             # {"appkey":"87e61042113142eb919a682aab37dbd7","appid":"5b68f482","authid":"0dcc0cd2b214b9f2210dbe9877113040"},
#             # {"appkey":"55e7e31dfdfa46b78a53ea89901992f1","appid":"5b69023c","authid":"2d19a80d2248a51b18346c1346af9ad1"},
#             # {"appkey":"ffe0060a357146aa9d9a1adb9a025c17","appid":"5b69117f","authid":"43ffc5bf77f7f88453d39e697a8b661b"},
#         ],
#     "industryid8":  # 信用卡
#         [
#             {"appkey": "e9c5f49217bc4f1eae6f2fc80072ae72", "appid": "5b1e4b0a",
#              "authid": "7a926171b3f49fa54d1714f6f40aa1cd"},
#             {"appkey": "9cdf09de9ac344d68ee6cac4532e35ce", "appid": "5b6427e5",
#              "authid": "cdd51750f9b4d1e612cd7c4d20969887"},
#             {"appkey": "f471e8fe65174b298c2cfc8a204c7ad8", "appid": "5b642811",
#              "authid": "1e61ffa43b5912c3fabcea5a32d13730"},
#             {"appkey": "38c579aa495242b5acf385e3a8573746", "appid": "5b642838",
#              "authid": "3e8e3ed9e922aaeb2c581ee38d3c5556"},
#             {"appkey": "49bfa2af82414d91851b34b081e8380a", "appid": "5b642860",
#              "authid": "ee4968d33f9f8168919bda7290bc1d19"},
#             {"appkey": "977559f724ac42ec8b075d2efcd546d7", "appid": "5b64288d",
#              "authid": "9b229d602692e804b70a4618af139f7e"},
#
#             # {"appkey":"6cfb4541c88c4bb6bf2fcd111c2f2398","appid":"5b681853","authid":"bc1ad127cb0cb5462a3d4b3d0305513a"},
#             # {"appkey":"be2658ba264e4d05a8b50af024e56e7a","appid":"5b68f4cd","authid":"0260c12c42537cf9435794b65a92d44d"},
#             # {"appkey":"3f206e026ca7446a9c9666a1f9c94e6f","appid":"5b690275","authid":"395f0a78679d21e2a17b71f93277151f"},
#             # {"appkey":"066c214c27e14c92b444a5ee154ecdff","appid":"5b6911b6","authid":"36dea10bcc419c9480996ae1c9165f84"},
#             # {"appkey":"8e6cc82a78094b9cb639201e3ccf4f79","appid":"5b7e7011"},
#             # {"appkey":"5caf4e32097241206c21e359dda989a4","appid":"5b7e7b13"},
#         ],
#     "industryid10":  # 发票
#         [
#             {"appkey": "7021dc9405424cf79c0afa753e0086aa", "appid": "5b17f776",
#              "authid": "c3b928b2eb27f65da63063df9827065b"},
#             {"appkey": "e4dac1413b3343719c6e88d5a2ad1cba", "appid": "5b6417c9",
#              "authid": "f22b6868c867ca37c07c37674d0a1807"},
#             {"appkey": "d90488e6720d4c3ab70d9518eeff4fea", "appid": "5b641928",
#              "authid": "89197ad2bcd078276704d45d179fcdb4"},
#             {"appkey": "4983c3cb3d674fb581b03a5e94a4f302", "appid": "5b6419a6",
#              "authid": "ce5aa94dcc7177f5456e7e66983cc028"},
#             {"appkey": "815cb77ae2324155b64c44e09b827ab4", "appid": "5b641a5f",
#              "authid": "980ec1e6d847690a5663ba43b055dfed"},
#             {"appkey": "09056b8f8e7242f2a56279491c0a3f15", "appid": "5b641adf",
#              "authid": "5e11130b934fc7a62f5c07751e86547f"},
#
#             # {"appkey":"bf06563436404bcd8724ed7e5ec4a028","appid":"5b6818b2","authid":"9b2a2854b31659a93b88f246250dcc0d"},
#             # {"appkey":"7faaa292fbe349a388c61336e5460028","appid":"5b68f50a","authid":"34dd7b2425825890292bed0998ecdd01"},
#             # {"appkey":"1b798daa428d463e8219072ec7df5fd2","appid":"5b6902b6","authid":"64deaf838116506746add835dad4f2c2"},
#             # {"appkey":"1b0d47017bec4a4dbdb6da7ea794796c","appid":"5b6911f1","authid":"edea340be97a348b880ce711f90fb32a"},
#         ],
#     "industryid11":  # 减肥回访
#         [
#             {"appkey": "76e0db60e26449409bf6e8abc72189d6", "appid": "5b3ad71f",
#              "authid": "14646e5fab8117a83693cfdb3b0dfa98"},
#             {"appkey": "8362d5262f764ef4965123e92a09a0ab", "appid": "5b642963",
#              "authid": "ff84398bad9a543dee1909f5cca36dec"},
#             {"appkey": "97d2a56fed774fa28b96c42bf30c1716", "appid": "5b64298d",
#              "authid": "f8404b93c8a4ccbf964f1513ede743e4"},
#             {"appkey": "b40b7a0ab7744d4ebc2826d7287e903b", "appid": "5b6429b4",
#              "authid": "7ce7d0e21298c0da4852ac69d6e0c1e6"},
#             {"appkey": "172617d5c57c4f64bfca15a2d7e8fa14", "appid": "5b6429df",
#              "authid": "78e174ebc3ea0b436f776b3eba08d920"},
#             {"appkey": "61db5d47b77345948ba9f5fbe685ba3e", "appid": "5b642a11",
#              "authid": "03e027c0fad538942d88d7e8650a0d0d"},
#
#             # {"appkey":"57d6b7c8196e47c2a992512f8c8346cc","appid":"5b681a3b","authid":"d59dab27a731832e858abee723d92254"},
#             # {"appkey":"c0b8c076774d44c8a1d81a26e4720c98","appid":"5b68f544","authid":"25a8ad02e1de2344c89b430fa8286610"},
#             # {"appkey":"7dfedb2275f7463b9189c350f0627189","appid":"5b69030d","authid":"5098b31921a53ae3596102c02ecc4c14"},
#             # {"appkey":"321e28cddae340adb48a7fc76df13f7a","appid":"5b69122f","authid":"0e1bbc12a8b7b73395be2cd1e4764ef1"},
#         ],
#     "industryid12":  # 招聘
#         [
#             {"appkey": "cc9f6910f9b04bf4b3e52845be38c93f", "appid": "5b505e3b",
#              "authid": "b7c5076a6c7d2412be2ed494e3ce010b"},
#             {"appkey": "335f2128189649a4bc245c6cb2b1f1c1", "appid": "5b642ae3",
#              "authid": "6d392075c15d9f4599ce78505ca9d49f"},
#             {"appkey": "e326234954e54ad99594d7f9ff58c6b8", "appid": "5b642b0d",
#              "authid": "9b229a3382db0aa50d91571b932a5b60"},
#             {"appkey": "628a97aad33444e4853cefdc6f34d6b4", "appid": "5b642b34",
#              "authid": "4a2a929ac834d1ff4d7e64184d622f04"},
#             {"appkey": "9a256bdbb81e4030abc97e7cba10f043", "appid": "5b642b6a",
#              "authid": "9034f1a550456749d7b33cea4aa187e9"},
#             {"appkey": "8d77495771a84c718d7a11c1a5fef088", "appid": "5b642b9b",
#              "authid": "235f03f742ab01c9e97a468c6e32f1a7"},
#
#             # {"appkey":"76b4cd9362d243b684e4813a59fd48e9","appid":"5b681a84","authid":"165db4876ef9459219e176eb5224efb5"},
#             # {"appkey":"5c3325b5aea9461a9505e0769eb0e1b3","appid":"5b68f580","authid":"203c732846436cc3c66d399d9ac82e69"},
#             # {"appkey":"f62b478391d947b3a083970c565baf48","appid":"5b690441","authid":"1bb22f08e1fedbc3ba22d4ca86eb6231"},
#             # {"appkey":"2a26142fbb30471e8557af6cec6d792b","appid":"5b691278","authid":"b442cc1ce98aafced23835026f4ed72c"},
#         ],
#     "industryid13":  # 广告
#         [
#             {"appkey": "54017e4f5dbb4be3950dc5afe540e845", "appid": "5b56d8b9",
#              "authid": "fd63e1201047cff2e5fb0adc7eec3dd0"},
#             {"appkey": "906495143b0e4aba9d654f0474b45d1b", "appid": "5b642c4e",
#              "authid": "7799fc5682e81b2b7fd8a245122ff516"},
#             {"appkey": "77864989ed9e416cb1edc2c08a8a67ed", "appid": "5b642caa",
#              "authid": "0233238f1f21abed9a1a60f3ae3378ae"},
#             {"appkey": "be7a937d4ea3405ba2331cc2fe0fcb5c", "appid": "5b642cd4",
#              "authid": "181dc1145d3869e922b2693f63ec7510"},
#             {"appkey": "bb337175f3a14fa79e8f567efa6af03c", "appid": "5b642cf9",
#              "authid": "8b6fcfcf0b18b2b36f4e799cc3292be9"},
#             {"appkey": "2f16b4494ed44446994058060fd1f104", "appid": "5b642d21",
#              "authid": "e276dd02abd3b1e6cdc288759e63ac10"},
#
#             # {"appkey":"ed971b58294b457e8ea9d47d7bbafed0","appid":"5b681ada","authid":"5c911b0e1adee14ea23a6ed4109896f5"},
#             # {"appkey":"415b5e333a38472b8b64c5f024c59ff4","appid":"5b68f5b8","authid":"a86ef42e448559f7f92f339cb0da08cd"},
#             # {"appkey":"816e4dd1908f448c96d6bfdee8dd7cac","appid":"5b69048c","authid":"95b3602f01e84e96114f16b0620bc046"},
#             # {"appkey":"06a08cf4e6cb4998ac2af8f7698c9234","appid":"5b6912b6","authid":"7e9d2a62cb487ce6e4f91ff62335abcd"},
#         ],
#     "industryid14":  # 电信
#         [
#             {"appkey": "8de0ce495e9a40ba848eac45eba96f5b", "appid": "5b6975de",
#              "authid": "b40cf5e7500ba545f09203e731bee9d9"},
#
#             {"appkey": "8631309a46d1415189a6df26810e1811", "appid": "5b6a94a1",
#              "authid": "6497db895cfd939b8df8950b6a2d8914"},
#             {"appkey": "c052a45ec4d342ecab3b483dae0a94fa", "appid": "5b6a955b",
#              "authid": "97b925351b14c6dbb7ded2c69c2c6465"},
#             {"appkey": "305f8b6f90b548ba9b58459e1011e649", "appid": "5b6a95d9",
#              "authid": "37fc6e7481cc1f32cb9291c73573bfb7"},
#             {"appkey": "4ba67adbc58d4369a9b9d3454c9c8d1d", "appid": "5b6a9680",
#              "authid": "f9fb18b96e9281b4c1b5241a9cc48a03"},
#         ]
# }
industryidalldata = {"industryid0":  # 默认
                     [
                         {"appkey": "8e6cc82a78094b9cb639201e3ccf4f79", "appid": "5b7e7011"},
                         {"appkey": "5caf4e32097241206c21e359dda989a4", "appid": "5b7e7b13"},
                     ]

                     }

industryiddata = OrderedDict(industryidalldata)


# 翻译接口
def preventwav(industryid, file):
    try:
        filedata = industryidalldata['industryid0']
        num = random.randint(0, len(filedata) - 1)
        voicedata = getBody(file)
        getHeaderdata = getHeader(filedata[num]['appkey'], filedata[num]['appid'], filedata[num]['authid'], file)

        starttime = time.time()
        URL = "https://openapi.xfyun.cn/v2/aiui"
        r = rs.post(URL, headers=getHeaderdata, data=voicedata, timeout=4)

        voice_logger.info('data:%s r:%s file:%s' % (filedata, r, file))
        elapsedendtime = r.elapsed
        data = r.json()
        r.close()
        endtime = time.time()
        alltime = endtime - starttime

        if str(data["code"]) != "0":
            voice_logger.warning('data:%s filedata:%s file:%s' % (data, filedata, file))
        voice_logger.info(
            'data:%s datanum:%s file:%s time:%s elapsedendtime:%s' % (data, num, file, alltime, elapsedendtime))

        if str(data["code"]) == "0":
            haveword = ''
            for respective in data["data"]:
                if 'text' in respective.keys():
                    if respective["text"] != '':
                        if len(respective["text"]) > len(haveword):
                            haveword = respective["text"]
            return haveword
        else:
            voice_logger.info('data:%s datanum:%s file:%s' % (data, num, file))
            return ''
    except Exception as e:
        voice_logger.error('file:%s error:%s %s', file, type(e), e)
        return "err"


def getBodybase64(filepath):
    import base64
    import urllib.parse as urllib
    binfile = open(filepath, 'rb')
    try:
        data = binfile.read()
        base64_audio = base64.b64encode(data)
        body = urllib.urlencode({'audio': base64_audio})

        return body
    except:
        return ''
    finally:
        binfile.close()


def getHeaderold(API_KEY, APPID, file):
    import time
    import hashlib
    import base64
    param = {"engine_type": "sms16k", "aue": "raw", "scene": "main"}

    curTime = int(int(round(time.time() * 1000)) / 1000)

    x_param = base64.b64encode(json.dumps(param).replace(' ', '').encode('utf-8'))

    x_checksum_content = API_KEY + str(curTime) + str(x_param, 'utf-8')
    x_checksum = hashlib.md5(x_checksum_content.encode('utf-8')).hexdigest()

    header = {'X-Appid': str(APPID),
              'X-CurTime': str(curTime),
              'X-Param': x_param,
              'X-CheckSum': x_checksum,
              'User-Agent': 'User-Agent:Mozilla/5.0'
              }

    voice_logger.info(
        "header:%s file:%s API_KEY:%s x_checksum_content:%s curTime:%s " % (
            header, str(file), API_KEY, x_checksum_content, curTime)
    )
    return header


# 科大旧版本语音听写
def dictationkeda(industryid, file):
    import urllib.request
    import urllib
    try:

        filedata = industryidalldata['industryid0']
        num = random.randint(0, len(filedata) - 1)
        voicedata = getBodybase64(file)
        getHeaderdata = getHeaderold(filedata[num]['appkey'], filedata[num]['appid'], file)

        #
        starttime = time.time()
        URL = "http://api.xfyun.cn/v1/service/v1/iat"
        # r = rs.post(URL,  data = voicedata.encode('utf-8'), headers = getHeaderdata,timeout=4)
        req = urllib.request.Request(url=URL, data=voicedata.encode('utf-8'), headers=getHeaderdata, method='POST')
        r = urllib.request.urlopen(req, timeout=4)
        voice_logger.info('r:%s file:%s' % (r, file))
        data = json.loads(r.read().decode('utf-8'))
        r.close()
        endtime = time.time()
        alltime = endtime - starttime

        voice_logger.info("data:%s datanum:%s file:%s alltime:%s " % (data, num, str(file), alltime))
        if str(data["code"]) == "0":
            return data["data"]
        else:
            voice_logger.info("data:%s datanum:%s file:%s " % (data, num, str(file)))
            return ''
    except Exception as e:
        voice_logger.error('file:%s error:%s %s', file, type(e), e)
        return ""


class Ws_Param(object):
    # 初始化
    def __init__(self, APPID, APIKey, APISecret, AudioFile):
        self.APPID = APPID
        self.APIKey = APIKey
        self.APISecret = APISecret
        self.AudioFile = AudioFile

        # vinfo返回子句结果对应的起始和结束的端点帧偏移值。端点帧偏移值表示从音频开头起已过去的帧长度 1:开启  vad_eos音频中间有静音或者杂音音频超过了后端点

    # 生成url
    def create_url(self):
        url = 'wss://ws-api.xfyun.cn/v2/iat'
        # 生成RFC1123格式的时间戳
        now = datetime.datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        # 拼接字符串
        signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + "/v2/iat " + "HTTP/1.1"
        # 进行hmac-sha256进行加密
        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()
        signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
            self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
        # 将请求的鉴权参数组合为字典
        v = {
            "authorization": authorization,
            "date": date,
            "host": "ws-api.xfyun.cn"
        }
        # 拼接鉴权参数，生成url
        url = url + '?' + urlencode(v)
        return url


def kedasocketapi(APPID, APIKey, APISecret, AudioFile):
    # 收到websocket消息的处理
    def on_message(ws, message):
        try:
            code = json.loads(message)["code"]
            sid = json.loads(message)["sid"]
            if code != 0:
                errMsg = json.loads(message)["message"]
                weixin_push(str(errMsg), str(code) + " sid " + str(sid), "科大翻译出错！！")
                voice_logger.warning("error:%s voice_dress:%s  " % (errMsg, AudioFile))

            else:
                data = json.loads(message)["data"]["result"]["ws"]
                result = ""
                for i in data:
                    for w in i["cw"]:
                        result += w["w"]
                the_result = memcachcon.if_exist(str(conn.basedbname) + 'keda' + str(AudioFile.split("/")[-1]))
                if memcachcon.if_exist(str(conn.basedbname) + 'keda' + str(AudioFile.split("/")[-1])) != None:
                    memcachcon.set_cach(str(conn.basedbname) + 'keda' + str(AudioFile.split("/")[-1]),
                                        str(the_result) + str(result))
                else:
                    memcachcon.set_cach(str(conn.basedbname) + 'keda' + str(AudioFile.split("/")[-1]), result)
                # return result

        except Exception as e:
            weixin_push(str(AudioFile), str(e), "科大翻译出错！！")
            voice_logger.error('errMsg:%s voice_dress：%s error:%s %s', errMsg, AudioFile, type(e), e)

    # 收到websocket错误的处理
    def on_error(ws, error):
        weixin_push(str(AudioFile), str(error), "科大翻译出错！！")
        voice_logger.warning("error:%s voice_dress:%s" % (error, AudioFile))

    # 收到websocket关闭的处理
    def on_close(ws):
        voice_logger.info("voice_dress:%s" % (AudioFile))

    STATUS_FIRST_FRAME = 0  # 第一帧的标识
    STATUS_CONTINUE_FRAME = 1  # 中间帧标识
    STATUS_LAST_FRAME = 2  # 最后一帧的标识

    def run(*args):
        frameSize = 8000  # 每一帧的音频大小
        intervel = 0.04  # 发送音频间隔(单位:s)
        # 公共参数(common)
        CommonArgs = {"app_id": APPID}
        # 业务参数(business)，更多个性化参数可在官网查看#iat：日常用语  #mandarin：中文普通话、其他语种
        BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin", "vinfo": 0,
                        "vad_eos": 10000}

        status = STATUS_FIRST_FRAME  # 音频的状态信息，标识音频是第一帧，还是中间帧、最后一帧
        # print('ffffssssss')
        voice_logger.info('voice_dress:%s' % AudioFile)
        with open(AudioFile, "rb") as fp:
            while True:
                buf = fp.read(frameSize)
                if not buf:
                    status = STATUS_LAST_FRAME
                # 第一帧处理
                # 发送第一帧音频，带business 参数
                # appid 必须带上，只需第一帧发送
                if status == STATUS_FIRST_FRAME:
                    d = {"common": CommonArgs,
                         "business": BusinessArgs,
                         "data": {"status": 0, "format": "audio/L16;rate=8000",
                                  "audio": str(base64.b64encode(buf), 'utf-8'),
                                  "encoding": "raw"}}
                    d = json.dumps(d)
                    ws.send(d)
                    status = STATUS_CONTINUE_FRAME
                # 中间帧处理
                elif status == STATUS_CONTINUE_FRAME:
                    d = {"data": {"status": 1, "format": "audio/L16;rate=8000",
                                  "audio": str(base64.b64encode(buf), 'utf-8'),
                                  "encoding": "raw"}}
                    ws.send(json.dumps(d))
                # 最后一帧处理
                elif status == STATUS_LAST_FRAME:
                    d = {"data": {"status": 2, "format": "audio/L16;rate=8000",
                                  "audio": str(base64.b64encode(buf), 'utf-8'),
                                  "encoding": "raw"}}
                    ws.send(json.dumps(d))
                    time.sleep(0.2)
                    break
                # 模拟音频采样间隔
                time.sleep(intervel)
        ws.close()

    # 收到websocket连接建立的处理
    def on_open(ws):
        threadvoicekeda.start_new_thread(run, ())

    wsParam = Ws_Param(APPID=APPID, APIKey=APIKey,
                       APISecret=APISecret,
                       AudioFile=AudioFile)
    websocket.enableTrace(False)
    wsUrl = wsParam.create_url()
    voice_logger.info('voice_dress:%s' % wsParam.AudioFile)

    ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)
    ws.on_open = on_open
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})


# 语音听写（新版本）
def newdictationkeda(industryid, file):
    import urllib.request
    import urllib
    try:

        filedata = industryiddata['industryid' + str(industryid)]
        num = random.randint(0, len(filedata) - 1)
        voicedata = getBodybase64(file)
        getHeaderdata = getHeaderold(filedata[num]['appkey'], filedata[num]['appid'], file)
        starttime = time.time()
        URL = "http://api.xfyun.cn/v1/service/v1/iat"
        req = urllib.request.Request(url=URL, data=voicedata.encode('utf-8'), headers=getHeaderdata, method='POST')
        r = urllib.request.urlopen(req, timeout=4)

        voice_logger.info('r:%s file:%s' % (r, file))
        data = json.loads(r.read().decode('utf-8'))
        r.close()
        endtime = time.time()
        alltime = endtime - starttime

        voice_logger.info('data:%s datanum:%s file:%s alltime:%s', data, num, file, alltime)

        if str(data["code"]) == "0":
            return data["data"]

        else:
            voice_logger.info('data:%s datanum:%s file:%s', data, num, file)
            return ''
    except Exception as e:
        voice_logger.error('file:%s error:%s %s', file, type(e), e)
        return ""


def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)  # ctypes.py_object(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    web_logger.info('tid:%s res:%s', tid, res)

    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")


def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)


def speakdiry(text, file):
    try:
        voice_logger.info('file:%s text:%s', file, text)
        global baiduapitoken
        urllink = 'https://aip.baidubce.com/rest/2.0/antispam/v2/spam?access_token=' + str(baiduapitoken)
        boby = {'content': str(text)}
        req = rs.post(urllink, data=boby, timeout=5)
        # req = rs.post(urllink, timeout=60)
        data = req.json()

        req.close()
        voice_logger.info('file:%s text:%s data:%s', file, text, data)
        if 'error_code' in data.keys():
            if str(data['error_code']) == '111' or str(data['error_code']) == '110':
                apitaken = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=wVijsc3uL8R0hWvc8nK3SbAK&client_secret=hMt8Ij0i0xAy85o8vYTf4O0FdSRA6kYe'
                req = rs.post(apitaken)
                apidata = req.json()
                if 'access_token' in apidata.keys():
                    baiduapitoken = apidata['access_token']
        if str(data['result']['spam']) == '1':
            return '1'
        return ''
    except Exception as e:
        voice_logger.warning('file:%s text:%s error:%s %s', file, text, type(e), e)
        return ''


# 语音合成(判断是否脏话)
def Voicerecognitiondirty(industryid, file, begindata):
    try:
        backA = preventwav(industryid, file)

        if backA != "err":
            data = backA
            ifdirty = ''
            if backA != "":
                ifdirty = speakdiry(backA, file)
            voice_logger.info('data:%s ifdirty:%s  file:%s  backtime:%s' %
                              (data, ifdirty, file, time.time() - begindata))
            backtuple = {"code": "1", "text": data, "file": file, 'dirty': ifdirty}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon
        else:
            backtuple = {"code": "-2", "text": '', "file": file, 'dirty': ''}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon

    except Exception as e:
        voice_logger.error('error:%s %s', type(e), e)
        backtuple = {"code": "-1", "text": '', "file": file, 'dirty': ''}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon


def get_sex_data(file):
    # global seg_sex
    # print('',file)
    try:
        segsex = ''  # Segmenter()
        sexdatalist = segsex(file)

        voice_logger.info('sex:%s file:%s', sexdatalist, file)
        # print(sexdatalist,)
        for d in sexdatalist:
            if 'male' in d:
                return '1'
            elif 'female' in d:
                return '2'
        return ''
    except Exception as e:
        print(e)
        return ''


# 获取appkey
def get_appkey_data(cid, file):
    try:
        queuedata = int(aliyunqueue.get(timeout=2))
        if queuedata >= aliyunallnum:
            data = queuedata - aliyunallnum
        else:
            data = queuedata
        # data = 1
        appKey = aliyundata[data]["appKey"]
        keyid = aliyundata[data]["keyid"]
        keysecret = aliyundata[data]["keysecret"]
        token = aliyundata[data]["token"]
        voice_logger.info('cid:%s data:%s queuedata:%s', cid, data, queuedata)

        bodyjson = getaliyunurl(file, appKey, token, 'false')  # false
        aliyunqueue.put(queuedata)
        bodyjson = json.loads(bodyjson)

        if bodyjson["status"] == 20000000:
            backtuple = {"code": str(1), "memo": '', 'sessionid': str(cid), 'appKey': str(appKey), 'keyid': str(keyid),
                         'keysecret': str(keysecret), 'token': str(token)}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon

        elif bodyjson["status"] == 40000001:
            newtoken = getaliyuntoken(keyid, keysecret)
            token = newtoken
            aliyundata[data]["token"] = newtoken
            bodyjson = getaliyunurl(file, appKey, token, 'false')
            bodyjson = json.loads(bodyjson)
            backtuple = {"code": str(1), "memo": '', 'sessionid': str(cid), 'appKey': str(appKey), 'keyid': str(keyid),
                         'keysecret': str(keysecret), 'token': str(token)}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon

        else:
            weixin_push(str(keyid), str(bodyjson), "获取appkey出错！！")
            voice_logger.warning('bodyjson:%s file:%s keyid:%s cid:%s', bodyjson, file, keyid, cid)
            backtuple = {"code": str(1), "memo": '', 'sessionid': str(cid), 'appKey': str(appKey), 'keyid': str(keyid),
                         'keysecret': str(keysecret), 'token': str(token)}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon
    except Exception as e:
        backtuple = {"code": str(-1), "memo": str(e), 'sessionid': '', 'appKey': '', 'keyid': '',
                     'keysecret': '', 'token': ''}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon


# 语音合成
@time_statistic()
def Voicerecognition(industryid, file, begindata):
    try:
        # threadKeda = ThreadWithReturnValue(target=preventwav, args=(industryid,file))
        # ff = preventwav(industryid,file)
        # print(ff)
        # dd = baiduVoicerecognition(industryid, file)
        # print(dd)
        # threadaliyun = ThreadWithReturnValue(target=processaliyun, args=(industryid,file))
        # threadKeda.start()
        # threadaliyun.start()
        # backA = threadaliyun.join()
        # print('backA',backA)
        # new = preventwav(0,file)
        # new1 = preventwav(1,file)
        # print('科大四川',new)
        # print('科大普通话',new1)
        # forsex = speed_process(file)
        # datafile, sampling_rate = librosa.load(file)
        # sig = [mean(d) for d in datafile]
        # forsex = recognizeGender({"signal": sig, "sampleRate": sampling_rate})
        # forsex = ''
        # threadsex = ThreadWithReturnValue(target=get_sex_data, args=(file, ))
        # threaddata = ThreadWithReturnValue(target=processaliyun, args=(file, industryid))
        #
        # threaddata.starft()
        # threadsex.start()
        # data = threaddata.join()
        # sex = threadsex.join()

        data = processaliyun(file, industryid)  # processaliyun(file, industryid)
        sex = ''
        # if len(data)>1 and len(data)<18:
        #     sex = get_sex_data(file)
        # backA = threadaliyun.join()
        # sex = main_sex(file)
        # data = processaliyun(file, industryid)  # 阿里的接口

        # data = Voicerecognitiontong(industryid,file,begindata)
        # data2 = processaliyun(file,1)
        # data = '嗯'
        # data = 'ky'
        # print('阿里云四川',data)
        # print('阿里云普通话',data2)

        # if (data == '喂' or len(data) != 1) and data != 'xplay':

        data = re.sub("[\s+\.\!\/_,$%^*(+\"\']+|[+——！，。？、~@#￥%……&*（）]+", " ", str(data))
        if data in ['嗯', '嗯嗯', '嗯喂', '喂', '嗯好', '嗯嗯嗯', '对嗯', '恩']:
            datakeda = dictationkeda(industryid, file)
            if datakeda == "":
                data = ""
        voice_logger.info('data:%s sex:%s file:%s backtime:%s', data, sex, file, time.time() - begindata)
        backtuple = {"code": "1", "text": data, "file": file, 'sex': sex}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon
    except Exception as e:
        voice_logger.warning('%s %s', type(e), e)
        backtuple = {"code": "-1", "text": '', "file": file, 'sex': ''}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon


# 语音合成
def Voicerecognitiontong(industryid, file, begindata):
    try:
        data = processatong(file)  # 捷通
        voice_logger.info('data %s  file %s  backtime %s', data, file, time.time() - begindata)
        backtuple = {"code": "1", "text": data, "file": file}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon
    except Exception as e:
        voice_logger.warning('%s %s', type(e), e)
        backtuple = {"code": "-1", "text": '', "file": file}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon


# 语音合成(需要转换语音格式)
def Voicechangerecognition(industryid, file, begindata):
    try:
        # 先转换录音文件
        backA = ''
        status = os.system('sh /usr/lzj/Pro/f112.sh ' + file)
        newfile = str(file).split('.')[0] + '_010.wav'

        code = status >> 16
        if code == 0:
            backA = preventwav(industryid, newfile)

        # if os.path.isfile(newfile):
        #   os.remove(newfile)
        if backA != "err":
            data = backA
            voice_logger.info('data:%s file:%s backtime:%s', data, file, time.time() - begindata)
            backtuple = {"code": "1", "text": data, "file": file}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon
        else:
            data = backA
            voice_logger.info('data:%s file:%s backtime:%s', data, file, time.time() - begindata)
            backtuple = {"code": "-2", "text": data, "file": file}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon
    except Exception as e:
        voice_logger.warning('%s %s', type(e), e)
        backtuple = {"code": "-1", "text": '', "file": file}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon


baidutokenvoice = '24.df23c1bb2b1bf79578961abab8709bbf.2592000.1542529956.282335-11054945'


# 调用百度翻译接口api
def baiduvoiceapi(pp, file):
    import requests
    import json
    import base64
    import os

    # 录音功能在另一个模块中实现，将录音功能存入本地文件中
    # 获取token
    cuid = "527263822"
    authUrl = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + \
        baiduapp.API_KEY + '&client_secret=' + baiduapp.SECRET_KEY
    response = rs.get(authUrl)

    res = json.loads(response.content)
    token = res['access_token']
    # 语音识别

    srvUrl = 'http://vop.baidu.com/server_api?lan=zh' + '&cuid=' + cuid + '&token=' + token

    # 设置音频属性，根据百度的要求，采样率必须为8000，压缩格式支持pcm（不压缩）、wav、opus、speex、amr
    VOICE_RATE = 8000
    WAVE_FILE = file  # 音频文件的路径注意win下用/，\在python中有转意的含义
    WAVE_TYPE = "wav"
    # 打开音频文件，并进行编码
    with open(WAVE_FILE, "rb") as f:
        speech_data = f.read()
        # 进行编码
        speech_base64 = base64.b64encode(speech_data).decode('utf-8')
    # size = len(speech_data)
    size = os.path.getsize(WAVE_FILE)
    update = json.dumps(
        {'format': WAVE_TYPE, 'rate': VOICE_RATE, 'channel': 1, 'cuid': "E4-02-9B-ZZ-YY-XX", 'token': token,
         'speech': speech_base64, 'len': size}).encode('utf-8')

    httpHeaders = {
        'Content-Type': 'audio/wav;rate=8000',
    }
    response = requests.post(srvUrl, headers=httpHeaders, data=update)

    res = json.loads(response.content)

    text = res['result'][0]

    # import base64
    # URL = "http://vop.baidu.com/server_api"
    # APP_ID = '11054945'
    # API_KEY = 'MgZuyYSa21sGg7ss7bDR8Iyb'
    # SECRET_KEY = 'b2532694b2eeb10468e82a828eecb976'
    #
    # params = {"token":""}
    # headers = {
    #     #"Content-Type": "audio/wav",
    #     "rate" : str(8000)
    #
    #     #'X-lan': x_checksum,
    # }
    # data = {
    #     'X-cuid': "00:16:3e:0e:97:40 brd ff:ff:ff:ff:ff:ff",
    #     'X-token': baidutokenvoice,
    #     'X-dev_pid': 1537,
    # }
    # voicedata = getBody(file)
    # r = rs.post(URL, data=data, params=params, body = voicedata,#(self.__connectTimeout,self.__socketTimeout,)
    #                         headers=headers, verify=False, timeout=4)
    #     #r = rs.post(URL, headers=getHeaderdata, data=voicedata)
    # data =  r.json()
    # print(data)


def getbaidu(talk, text):
    from ..aip import AipNlp

    """ 你的 APPID AK SK """
    APP_ID = '10882358'
    API_KEY = 'kUjDwWrWWXsHrTHrGwD1ujZL'
    SECRET_KEY = 'K4V8k0WX0WUxZAjQOS7GlbNpoSAu8Skv'

    client = AipNlp(APP_ID, API_KEY, SECRET_KEY)

    """ 调用对话情绪识别接口 """

    """ 如果有可选参数 """
    options = {}
    options["scene"] = str("talk")

    """ 带参数调用对话情绪识别接口 """
    return client.emotion(text, options)


def text_detection(text):
    # """ 你的 APPID AK SK """
    APP_ID = '11325623'
    API_KEY = 'wVijsc3uL8R0hWvc8nK3SbAK'
    SECRET_KEY = 'hMt8Ij0i0xAy85o8vYTf4O0FdSRA6kYe'

    client = AipContentCensor(APP_ID, API_KEY, SECRET_KEY)
    # """ 带参数调用对话情绪识别接口 """
    return client.textCensorUserDefined(text)


# baiduVoicerecognitiontoken="24.211321928b104342160b0ad4bc67d920.2592000.1536199584.282335-11054945"
# 百度语音翻译
def baiduVoicerecognition(industryid, file):
    try:
        num = random.randint(0, 4)
        voice_logger.info('file:%s industryid:%s', file, industryid)
        voicefile = getBody(file)
        data = {}
        if str(num) == '0':
            data = baiduapp.client0.asr(voicefile, 'wav', 8000, {'dev_pid': '1536', })
        elif str(num) == '1':
            data = baiduapp.client1.asr(voicefile, 'wav', 8000, {'dev_pid': '1536', })
        elif str(num) == '2':
            data = baiduapp.client2.asr(voicefile, 'wav', 8000, {'dev_pid': '1536', })
        elif str(num) == '3':
            data = baiduapp.client3.asr(voicefile, 'wav', 8000, {'dev_pid': '1536', })
        else:
            data = baiduapp.client4.asr(voicefile, 'wav', 8000, {'dev_pid': '1536', })
        voice_logger.info('num:%s data:%s file:%s', num, data, file)
        if str(data["err_msg"]) == "success.":
            if 'result' in data:
                res = data["result"]
                if len(res) > 0:
                    return res[0]
        return ''
    except Exception as e:
        voice_logger.warning('file:%s  error:%s %s', file, type(e), e)
        return ''


@time_statistic(3, 'cid')
def beginsentences(cmpid, serviceid, sessionid, cid, operation, session_data, session_sort, userid, dbname):
    prologue = selprologue(cmpid, serviceid, dbname, cid)
    web_logger.info('cid:%s operation:%s cmpid:%s prologue:%s', cid, operation, cmpid, prologue)
    #  h.HoodleMobileadress,h.HoodleMobileid,h.type,h.qtype,h.sceneid,h.remark,interrupt,skill,h.voxfile,h.questionnairetype,h.matchidlist
    if len(prologue) > 0:
        # 查询态度流转
        prologue = prologue[0]
        web_logger.info(
            'cid:%s operation:%s cmpid:%s HoodleMobileadress:%s HoodleMobileid:%s type:%s qtype:%s sceneid:%s '
            'remark:%s interrupt:%s skill:%s voxfile:%s questionnairetype:%s matchidlist:%s', cid, operation, cmpid,
            *prologue)
        if prologue[9] and prologue[10]:
            memcachcon.set_cach(str(conn.basedbname) + 'questionnairetype' + str(prologue[1]) + str(cid),
                                prologue[9])
            memcachcon.set_cach(str(conn.basedbname) + 'matchidlist' + str(prologue[1]) + str(cid), prologue[10])

        skill = prologue[7]
        HoodleMoboleid = prologue[1]
        insertaskbeginandend(cmpid, HoodleMoboleid, cid, prologue[4], dbname)
        backchangedata = changebackdataforTTS(prologue[3], prologue[2], prologue[0],
                                              prologue[5], prologue[8], cmpid, userid, cid, dbname)
        web_logger.info('cid:%s operation:%s cmpid:%s backchangedata:%s voflie:%s skill:%s', cid, operation,
                        cmpid, backchangedata, prologue[8], skill)
        tupledata = (
            backchangedata['backtext'], backchangedata['backtype'], 1, '', 'open', HoodleMoboleid, '', '', '',
            backchangedata['backremark'], '', prologue[6], '',
            '', '', '', '', session_data, session_sort)
        return recordbackdataforquestionnotinsert(4, tupledata, sessionid, cid, operation, '', '', dbname)
    else:  # 557788
        return recordbackdataforquestionnotinsert(4, (
            '你连开场白都不设置，你想怎么聊', 1, 1, '', 'close', '', '', '', '', '', '', '', '', '', '', '', '', session_data,
            session_sort), sessionid, cid, operation, '', '', dbname)


# hello先
@time_statistic(3, 'cid')
def sayhello(cmpid, serviceid, sessionid, cid, operation, session_data, session_sort, userid, dbname):
    hello = selcommon(cmpid, serviceid, 1, 'hello', dbname, cid)  #

    if len(hello) != 0:
        back = globalvariable(hello[0][0], hello[0][1], hello[0][2], hello[0][3], cid, cmpid, serviceid, '', 'hello',
                              '', hello[0][4], hello[0][5], hello[0][6], session_data, session_sort, userid, dbname)
        if back != None and len(back) != 0:
            return recordbackdataforquestionnotinsert(4, back, sessionid, cid, operation, '0', '2', dbname)


# 结束语
@time_statistic(3, 'cid')
def endsentences(cmpid, serviceid, sessionid, cid, operation, pipetype, num, session_data, session_sort, userid,
                 dbname):
    prologue = selTAG(cmpid, serviceid, dbname, cid)
    web_logger.info('cid:%s operation:%s cmpid:%s prologue:%s', cid, operation, cmpid, prologue)

    # h.HoodleMobileadress,h.HoodleMobileid,h.type,h.qtype,h.sceneid,h.remark,interrupt,h.voxfile
    if str(len(prologue)) != '0':
        prologue = prologue[0]
        web_logger.info(
            'cid:%s operation:%s cmpid:%s HoodleMobileadress:%s HoodleMobileid:%s type:%s qtype:%s sceneid:%s '
            'remark:%s interrupt:%s voxfile:%s', cid, operation, cmpid,
            *prologue)
        # 插入结束语记录zt_know_ask
        insertaskbeginandend(cmpid, prologue[1], cid, prologue[4], dbname)
        backchangedata = changebackdataforTTS(prologue[3], prologue[2], prologue[0],
                                              prologue[5], prologue[7], cmpid, userid, cid, dbname)

        tupledata = (
            backchangedata['backtext'], backchangedata['backtype'], 1, '', 'close', prologue[1], '', '', '',
            backchangedata['backremark'], '', '', '', '', '',
            pipetype, num, session_data, session_sort)  # 557788

        return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, prologue[6], '', dbname)
    else:  # 557788
        return recordbackdataforquestion(4, (
            '亲，没有配置结束语呢', 1, 1, '', 'close', '', '', '', '', '', '', '', '', '', '', '', '', session_data,
            session_sort),
            sessionid, cid, operation, '', '', dbname)


def endsentencestuple(cmpid, serviceid, sessionid, cid, operation, session_data, session_sort, userid, dbname):
    prologue = selTAG(cmpid, serviceid, dbname, cid)
    # h.HoodleMobileadress,h.HoodleMobileid,h.type,h.qtype,h.sceneid,h.remark,interrupt,h.voxfile
    tupledata = ()
    # 插入结束语记录zt_know_ask
    insertaskbeginandend(cmpid, prologue[0][1], cid, prologue[0][4], dbname)

    if str(len(prologue)) != '0':
        # HoodleMobileadress = str(prologue[0][0])
        # remark = ''
        # backtype = 1
        backchangedata = changebackdataforTTS(prologue[0][3], prologue[0][2], prologue[0][0],
                                              prologue[0][5], prologue[0][7], cmpid, userid, cid, dbname)

        tupledata = (
            backchangedata['backtext'], backchangedata['backtype'], 1, '', 'close', prologue[0][1], '', '', '',
            backchangedata['backremark'], '', '', '', '', '',
            '', '', session_data, session_sort)  # 557788

    return tupledata


dictrobotdata = {}


# 判断是否配置机器人
def selallrobot(dbname, cid):
    # sql = "select cr.onserviceid,industryid  from zt_cmp_robot cr where cr.state=1 and cr.onserviceid is not null and cr.onserviceid !=0 ;"
    sql = "select cr.onserviceid,industryid  from zt_cmp_robot cr where cr.onserviceid is not null and cr.onserviceid !=0 ;"
    ifopen = conn.mysql_sel(sql, dbname, cid)
    for data in ifopen:
        dictrobotdata['serviceid' + str(data[0])] = {'industryid': data[1]}
    return ifopen


# 添加没有存储的机器人
def addrobottodict(serviceid, dbname, cid):
    sql = "select cr.onserviceid,industryid  from zt_cmp_robot cr where cr.state=1 and cr.onserviceid is not null and cr.onserviceid !=0 and cr.onserviceid='" + str(
        serviceid) + "' "
    ifopen = conn.mysql_sel(sql, dbname, cid)
    for data in ifopen:
        dictrobotdata['serviceid' + str(data[0])] = {'industryid': data[1]}
    return ifopen


# 删除缓存
@time_statistic(0, 'cid')
def delallcach(cid, data, dbname):
    if memcachcon.if_exist(str(dbname) + 'cache' + str(cid)) != None:  # 久不应答判断是否连续（no_input）
        memcachcon.del_cach(str(dbname) + 'cache' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'nospeakcache' + str(cid)) != None:  # 久不应答次数
        memcachcon.del_cach(str(dbname) + 'nospeakcache' + str(cid))
    # if memcachcon.if_exist(str(dbname)+'interrupt' + str(cid)) != None:
    #     memcachcon.del_cach(str(dbname)+'interrupt' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'sendmessage' + str(cid)) != None:  # 记录是否发了短信
        memcachcon.del_cach(str(dbname) + 'sendmessage' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'textnull' + str(cid)) != None:  # 记录连续not_word数
        memcachcon.del_cach(str(dbname) + 'textnull' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'textnullnum' + str(cid)) != None:  # 记录not_word轮询（not_word）
        memcachcon.del_cach(str(dbname) + 'textnullnum' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'comeagain' + str(cid)) != None:  # 记录重复提问次数（repeat）
        memcachcon.del_cach(str(dbname) + 'comeagain' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'nottime' + str(cid)) != None:  # 记录客户忙碌轮询（没空busy）
        memcachcon.del_cach(str(dbname) + 'nottime' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'profanity' + str(cid)) != None:  # 脏话轮询（dirty）
        memcachcon.del_cach(str(dbname) + 'profanity' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'answercach' + str(cid)) != None:  # 记录上个问题回答的问题库
        memcachcon.del_cach(str(dbname) + 'answercach' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'Jumpprocesses' + str(cid)) != None:  # 记录问题跳转的编码
        memcachcon.del_cach(str(dbname) + 'Jumpprocesses' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'notnextandbegin' + str(cid)) != None:  # 记录未知问题
        memcachcon.del_cach(str(dbname) + 'notnextandbegin' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'notnextagain' + str(cid)) != None:  # 未知问题轮询（to_much）
        memcachcon.del_cach(str(dbname) + 'notnextagain' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'await' + str(cid)) != None:  # 等待轮询（await）
        memcachcon.del_cach(str(dbname) + 'await' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'refusecount' + str(cid)) != None:  # 记录拒绝次数（refuse）
        memcachcon.del_cach(str(dbname) + 'refusecount' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'awaitcount' + str(cid)) != None:  # 是否处于等待状态
        memcachcon.del_cach(str(dbname) + 'awaitcount' + str(cid))

    if memcachcon.if_exist(str(dbname) + 'handover' + str(cid)) != None:  # 记录是否已经交接出去
        memcachcon.del_cach(str(dbname) + 'handover' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'childrobot' + str(cid)) != None:  # 记录子机器人之间的跳转
        memcachcon.del_cach(str(dbname) + 'childrobot' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'intentionrecord' + str(cid)) != None:  # 记录意图编码
        memcachcon.del_cach(str(dbname) + 'intentionrecord' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'nowexpression' + str(cid)) != None:  # 记录意图表达编码
        memcachcon.del_cach(str(dbname) + 'nowexpression' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'Globalgrooveid' + str(cid)) != None:  # 记录词曹编码
        memcachcon.del_cach(str(dbname) + 'Globalgrooveid' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'Globalfeedbackcount' + str(cid)) != None:  # 词曹轮询提问
        memcachcon.del_cach(str(dbname) + 'Globalfeedbackcount' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'Globalkeymainid' + str(cid)) != None:  # 记录词曹值编码
        memcachcon.del_cach(str(dbname) + 'Globalkeymainid' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'Globalnotinsertkey' + str(cid)) != None:  # 没有匹配到词曹
        memcachcon.del_cach(str(dbname) + 'Globalnotinsertkey' + str(cid))

    # if memcachcon.if_exist('backgrooveid' + str(cid)) != None:
    #     memcachcon.del_cach('backgrooveid' + str(cid))
    # if memcachcon.if_exist(str(dbname)+'sharetype' + str(cid)) != None:#分享机器人的定制流程编码
    #     memcachcon.del_cach(str(dbname)+'sharetype' + str(cid))
    if str(data) == '1':
        # if memcachcon.if_exist('Globalsessionsort' + str(cid)) != None:
        #     memcachcon.del_cach('Globalsessionsort' + str(cid))
        # if memcachcon.if_exist('Globalsessiondata' + str(cid)) != None:
        #     memcachcon.del_cach('Globalsessiondata' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'closecount' + str(cid)) != None:  # 轮询结束语
            memcachcon.del_cach(str(dbname) + 'closecount' + str(cid))
    elif str(data) == '2':
        if memcachcon.if_exist(str(dbname) + 'closecount' + str(cid)) != None:  # 轮询结束语
            memcachcon.del_cach(str(dbname) + 'closecount' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'TTS_voice' + str(cid)) != None:  # 声音大小
            memcachcon.del_cach(str(dbname) + 'TTS_voice' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'TTS_speed' + str(cid)) != None:  # 语速
            memcachcon.del_cach(str(dbname) + 'TTS_speed' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'TTS_informantid' + str(cid)) != None:  # TTS平台
            memcachcon.del_cach(str(dbname) + 'TTS_informantid' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'TTS_remark' + str(cid)) != None:  # 说话人
            memcachcon.del_cach(str(dbname) + 'TTS_remark' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'largestwordcount' + str(cid)) != None:  # 说话最大次数统计
            memcachcon.del_cach(str(dbname) + 'largestwordcount' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'largestword' + str(cid)) != None:  # 说话最大次数
            memcachcon.del_cach(str(dbname) + 'largestword' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'have_voiced' + str(cid)) != None:  # 说话最大次数
            memcachcon.del_cach(str(dbname) + 'have_voiced' + str(cid))


# 去重
def del_repetition_data(cid, dbname):
    selsql = "SELECT GROUP_CONCAT(a.askid)   from zt_know_ask a where a.session_data!='' and a.cid='" + str(
        cid) + "' GROUP BY a.session_data HAVING count(a.cid)>1"
    askid = conn.mysql_selrowid(selsql, dbname, cid)
    if askid != "":
        asklist = askid.split(',')

        sqldel = "delete from zt_know_ask where askid in " + str(tuple(asklist)) + ""

        conn.mysql_commit(sqldel, dbname, cid)
    selsql = "SELECT GROUP_CONCAT(a.respondid)   from zt_cmp_robot_respond a where a.session_data!='' and a.cid='" + str(
        cid) + "' GROUP BY a.session_data HAVING count(a.cid)>1"
    respondid = conn.mysql_selrowid(selsql, dbname, cid)
    if respondid != "":
        respondidlist = respondid.split(',')

        sqldel = "delete from zt_cmp_robot_respond where respondid in " + str(tuple(respondidlist)) + ""

        conn.mysql_commit(sqldel, dbname, cid)
    selsql = "SELECT GROUP_CONCAT(a.sesssionsceneid)   from zt_cmp_robot_sessionscene a where a.session_data!='' and a.cid='" + str(
        cid) + "' GROUP BY a.session_data HAVING count(a.cid)>1"
    sesssionsceneid = conn.mysql_selrowid(selsql, dbname, cid)
    if sesssionsceneid != "":
        sesssionsceneidlist = sesssionsceneid.split(',')

        sqldel = "delete from zt_cmp_robot_sesssionscene where sesssionsceneidlist in " + str(
            tuple(sesssionsceneidlist)) + ""

        conn.mysql_commit(sqldel, dbname, cid)
    selsql = "SELECT GROUP_CONCAT(a.sessionstorageid)   from zt_cmp_robot_sessionstorag a where a.session_data!='' and a.cid='" + str(
        cid) + "' GROUP BY a.session_data HAVING count(a.cid)>1"
    sessionstorageid = conn.mysql_selrowid(selsql, dbname, cid)
    if sessionstorageid != "":
        sessionstorageidlist = sessionstorageid.split(',')

        sqldel = "delete from zt_cmp_robot_sesssionstorag where sessionstorageid in " + str(
            tuple(sessionstorageidlist)) + ""

        conn.mysql_commit(sqldel, dbname, cid)


allrobotdata = selallrobot('', '')


# 查询全局拨打结果
def sel_global_calltype(dbname):
    try:
        sql = "SELECT GROUP_CONCAT(a.answer separator '|') from zt_know_answerid a where a.answertypeid=23"
        data = conn.mysql_selrowid(sql, dbname, '')
        if data:
            memcachcon.set_cach(str(dbname) + "calltype", str(data))
    except Exception as e:
        web_logger.warning('error:%s %s', type(e), e)


@time_statistic(0, 'cid')
# @profile_wrapper
def grphone(cid, text, who, cmpid, channelid, clevel, location, choiceback, serviceid, operation, askid, robot,
            storagetext, storagevoice, createtime, question, answer, answerattitude, wordslotid, session_data,
            session_sort, userid, peplesex, dbname, originalcmpid, get_digits=None):
    operation = str(operation)
    # 判断是否配置机器人
    if 'serviceid' + str(serviceid) not in dictrobotdata:
        addrobottodict(serviceid, dbname, cid)
    # 保存聊天记录
    if operation == '6':
        web_logger.info('保存聊天记录 cid:%s operation:%s cmpid:%s text:%s', cid, operation, cmpid, text)
        tupledata = ('', '', '', '0', 'open', askid, '', '', '1', '', '', '', '', '', '', '', '', session_data,
                     session_sort)  # 557788
        return recordbackdataforquestion(4, tupledata, '', cid, operation, '', '', dbname)
    # 电话添加问答
    elif operation == '7':
        answerid = insertanswer(cmpid, answer, dbname, cid)
        web_logger.info('电话添加问答 cid:%s operation:%s cmpid:%s text:%s question:%s answerid:%s', cid, operation, cmpid,
                        text, question, answerid)
        mongorobot.addstatement(str(cmpid) + '-service' + str(serviceid), question, 'A' + str(answerid), '', dbname)
        insertcount = insertquestion(cmpid, question, answerid, serviceid, dbname, cid)
        return backtypeaddphone(insertcount, cid, '', '', '', 'open', '', operation, '', '', '', '', '', '', '', '',
                                '', '', '', session_data, session_sort, dbname)  # 557788  返回json数据

    if memcachcon.if_exist(str(dbname) + 'childrobot' + str(cid)) != None:
        web_logger.info('cid:%s  原始serviceid:%s', cid, serviceid)
        serviceid = memcachcon.if_exist(str(dbname) + 'childrobot' + str(cid))

    # 8.未接原因
    if operation == '8':
        if text == '' or re.search('[a-zA-Z]', text):
            os.remove(config.voice_dress + storagevoice)
        else:
            import jieba
            jieba.add_word('通话中')
            cut_text = jieba.lcut(text)
            lcut_text = '  '.join(cut_text)
            voice_sql = "INSERT into voice_info(text,storagevoice,storagetext) VALUES ('" + \
                str(text)+"','"+str(storagevoice)+"','"+str(lcut_text)+"');"
            conn.mysql_insertid(voice_sql, dbname, cid)
        web_logger.info('前奏音检测 cid:%s operation:%s cmpid:%s text:%s', cid, operation, cmpid, text)
        for data in backclose:
            for datakey in data[1].split(','):
                if datakey in text:
                    tupledata = (
                        '', 9, 1, '', 'open', askid, '', '', '', data[0], '', '', '', '', '', '', '', session_data,
                        session_sort)  # 557788
                    return recordbackdataforquestionnotinsert(4, tupledata, '1', cid, operation, '', '', dbname)
        tupledata = ('', 9, 1, '', 'open', askid, '', '', '', 0, '', '', '', '', '', '', '', '', '', session_data,
                     session_sort)  # 557788
        return recordbackdataforquestionnotinsert(4, tupledata, '1', cid, operation, '', '', dbname)
    # 2：终止通话
    elif operation == '2':
        web_logger.info('终止通话 cid:%s operation:%s cmpid:%s text:%s', cid, operation, cmpid, text)
        delallcach(cid, 2, dbname)
        # inserscore(cid, cmpid, serviceid)
        tupledata = ('', '9', 1, '0', 'close', askid, '', '', '', '', '', '', '', '', '', '', '', session_data,
                     session_sort)  # 557788
        return recordbackdataforquestionnotinsert(4, tupledata, '1', cid, operation, '', '', dbname)
    # 1：创建新会话
    elif operation == '1':  # （1：创建新会话 2：终止通话 3：正常提问  4：主动提问  5:用户打断 6：保存聊天记录，7电话添加问答）
        # 查询和存储说话人
        speechdata = get_speech(serviceid, dbname, cid)
        web_logger.info('创建新会话 cid:%s text:%s operation:%s cmpid:%s speechdata:%s',
                        cid, text, operation, cmpid, speechdata)
        memcachcon.set_cach(str(dbname) + 'TTS_voice' + str(cid), speechdata[0]["voice"])
        memcachcon.set_cach(str(dbname) + 'TTS_speed' + str(cid), speechdata[0]["speed"])
        memcachcon.set_cach(str(dbname) + 'TTS_informantid' + str(cid), speechdata[0]["informantid"])
        memcachcon.set_cach(str(dbname) + 'TTS_remark' + str(cid), speechdata[0]["remark"])
        if speechdata[0]["largestwordnum"] != None and speechdata[0]["largestwordnum"] != "None" and speechdata[0]["largestwordnum"] > 0:
            memcachcon.set_cach(str(dbname) + 'largestword' + str(cid), speechdata[0]["largestwordnum"])
        delallcach(cid, 1, dbname)
        memcachcon.set_cach(str(dbname) + 'operation' + str(cid), 1)

        if originalcmpid != "" and originalcmpid != cmpid:
            # 查询复制机器人的定制流程编码
            memcachcon.set_cach(str(dbname) + 'sharecmpid' + str(cid), originalcmpid)
            htypeid = selcopychatterbottype(originalcmpid, serviceid, dbname, cid)
            if htypeid:
                memcachcon.set_cach(str(dbname) + 'sharetype' + str(cid), htypeid)

        # 记录挂断原因
        memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 3)
        back = sayhello(cmpid, serviceid, 1, cid, operation, session_data, session_sort, userid, dbname)
        if back != None:
            return back
        return beginsentences(cmpid, serviceid, 1, cid, operation, session_data, session_sort, userid, dbname)
    if 'serviceid' + str(serviceid) not in dictrobotdata:
        return backtypeaddphone(0, cid, 1, '用户还没配置机器人呢！请前往配置机器人！', '', 'close', '', -1, '', '', '', '', '', '', '', '',
                                '', '', '', session_data, session_sort, dbname)  # 557788
    robotdata = tuple(dictrobotdata['serviceid' + str(serviceid)].values())
    # 判断公司编码是否有效
    text = re.sub("[\s+\!\/_,$%^*(+\"\']+|[+——！，。？、~@#￥%……&*（）]+", "", text)
    memcachcon.set_cach(str(dbname) + 'Globalsessiondata' + str(cid), session_data)
    memcachcon.set_cach(str(dbname) + 'Globalsessionsort' + str(cid), session_sort)
    if memcachcon.if_exist(str(dbname) + 'istransfer' + str(cid)) != None and operation != '13' and str(
            operation) != '14':
        tupledata = ('已转人工后没有返回结果的流程忽略', 1, 3, '0', 'open', askid, '', '',
                     '7', '1', '', '', wordslotid, '', '', '4', '6', session_data, session_sort)  # 557788
        return recordbackdataforquestionnotinsert(4, tupledata, 1, cid, operation, '', '', dbname)
    # 插入调用机器人记录并返回编码
    sessionid = insetCallrecordsphone(cid, text, who, cmpid, channelid, clevel, location, serviceid, operation,
                                      session_data, session_sort, dbname)
    # 按键采集出错时在此保存
    if get_digits == "4":
        error_text_map = {'1': '正常', '2': '参数错误、按键创建失败', '3': '超时或输入错误'}
        error_text = error_text_map.get(text, "get_digits == '4'时 storagetext 不在可选范围 （1，2，3）")
        insertsessionstorage(2, error_text, storagevoice, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                             cid, operation, session_data, session_sort, peplesex, '', '', dbname, askid)
    else:
        insertsessionstorage(2, text, storagevoice, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), cid,
                             operation, session_data, session_sort, peplesex, '', '', dbname, askid)

    if sessionid == 0 or sessionid == conn.err:
        return backtypeaddphone(0, cid, 1, "插入调用机器人错误！", '', 'close', '', -1, '', '', '', '', '', '', '', '', '',
                                '', '', session_data, session_sort, dbname)  # 557788

    # 是否有声音
    if text != "" and memcachcon.if_exist(str(dbname) + 'have_voiced' + str(cid)) == None:
        memcachcon.set_cach(str(dbname) + 'have_voiced' + str(cid), 1)

    if operation == '13':  # 转接成功
        # 更新挂机原因
        memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 9)
        memcachcon.del_cach(str(dbname) + 'istransfer' + str(cid))
        tupledata = ('', 1, 3, '0', 'open', askid, '', '', '', '1', '', '', wordslotid, '', '', '2', '16',
                     session_data, session_sort)  # 557788
        return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)
    if operation != '5' and operation != '9':
        memcachcon.del_cach(str(dbname) + 'operation' + str(cid))
    if operation == '9':
        # 判断是否脏话
        specail = dirt_txt_back(text, cmpid, serviceid, cid, sessionid, operation, askid, session_data,
                                session_sort, userid, dbname)
        web_logger.info('cid:%s operation:%s cmpid:%s askid:%s text:%s specail:%s', cid, operation, cmpid, askid, text,
                        specail)
        if specail != None:
            return specail
        tupledata = (
            '打断忽略', 1, 3, '0', 'open', askid, '', '', '4', '1', '', '', wordslotid, '', '', '4', '1',
            session_data,
            session_sort)  # 557788
        return recordbackdataforquestion(4, tupledata, 1, cid, operation, '', '', dbname)
    # 技能
    if wordslotid != "" and text != "":
        # 收集下个数据
        # nextskill = selskill('',wordslotid)
        # 存储采集到的数据
        storagecollection(wordslotid, cid, text, dbname)
        # 技能类型 1信息采集 2接口调用
        skilltype = judgeskilltyoe(wordslotid, dbname, cid)

        nextskill = skillskip(skilltype[0][1], wordslotid, cid, askid, session_data, session_sort, dbname)

        if nextskill != None and len(nextskill) != 0:
            return recordbackdataforquestion(4, nextskill, sessionid, cid, operation, '', '', dbname)
        else:
            if skilltype != None and len(skilltype) != 0:
                # url
                if str(skilltype[0][0]) == '2':
                    url = jointurl(skilltype[0][1], cid, dbname)
                    # 调用接口返回json
                    urljson = invokingurljson(url, cid)

                    if 'err!!' in urljson:
                        tupledata = (
                            '调用第三方接口出错', 1, 1, '0', 'open', askid, '', '', '', '', '', '0', '', '', '', '', '',
                            session_data, session_sort)  # 557788
                        return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '',
                                                         dbname)

                    # 遍历返回的json数据
                    for key in urljson:
                        # 存储数据
                        selstoragejsonitem(wordslotid, key, urljson[key], cid, cmpid, dbname)

                data = endskillgather(skilltype[0][1], dbname, cid)

                typedata = 1
                content = data[0][2]
                backtext = data[0][0]
                if str(data[0][3]) == '2':  # 是变量
                    if str(data[0][1]) == '2':  # 是语音
                        typedata = 11
                        if content != "":
                            # print('5555555')
                            content = backvariant(content, cid, 2, cmpid, userid, dbname)
                        backtext = backvariant(backtext, cid, 2, cmpid, userid, dbname)
                    elif str(data[0][1]) == '1':  # 文本
                        typedata = 1
                        # print(6666666666)
                        content = backvariant(content, cid, 1, cmpid, userid, dbname)
                        backtext = backvariant(backtext, cid, 1, cmpid, userid, dbname)
                else:
                    if str(data[0][1]) == '2':  # 是语音
                        typedata = 9
                if str(skilltype[0][0]) == '1':  #
                    # 查询结束采集数据
                    tupledata = (
                        backtext, typedata, 1, '0', 'open', askid, '', '', '', content, '', '0', '', '', '', '',
                        '',
                        session_data, session_sort)  # 557788
                    return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)
                else:

                    tupledata = (
                        backtext, typedata, 1, '0', 'open', askid, '', '', '', content, '', '0', '', '', '', '',
                        '',
                        session_data, session_sort)  # 557788
                    return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)
    # hello之后执行开场白
    if str(askid) == '' and operation != '2' and str(text) != '' and operation != '4':

        # 主动提问编码和终止会话
        if memcachcon.if_exist(str(dbname) + 'textnull' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'textnull' + str(cid))
        return beginsentences(cmpid, serviceid, sessionid, cid, operation, session_data, session_sort, userid,
                              dbname)

    # 处于等待状态
    awaitcountdata = memcachcon.if_exist(str(dbname) + 'awaitcount' + str(cid))  # 查询
    if awaitcountdata != None:
        # 查询是否有数据
        if operation == '4':  # 久不应答
            # 查询是否是唤醒词
            if memcachcon.if_exist(str(dbname) + 'awaitcount' + str(cid)) != None:
                memcachcon.del_cach(str(dbname) + 'awaitcount' + str(cid))
            # del awaitcount[str(cid)]
            back = notspearkword(cmpid, serviceid, sessionid, cid, operation, askid, session_data, session_sort,
                                 userid, dbname)
            if back != None and len(back) != 0:
                return back

        if text == '':
            tupledata = (
                '等待', 1, 1, '0', 'open', askid, '', '', '3', '', '', '', '', '', '', '', '', session_data,
                session_sort)  # 557788
            return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)
        awaken = selcommon(cmpid, serviceid, awaitcountdata, 'awaken', dbname, cid)  #
        if memcachcon.if_exist(str(dbname) + 'awaitcount' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'awaitcount' + str(cid))

        if len(awaken) != 0:
            # del awaitcount[str(cid)]
            back = globalvariable(awaken[0][0], awaken[0][1], awaken[0][2], awaken[0][3], cid, cmpid, serviceid,
                                  askid, 'awaken', '', awaken[0][4], awaken[0][5], awaken[0][6], session_data,
                                  session_sort, userid, dbname)
            if back != None and len(back) != 0:
                return recordbackdataforquestion(4, back, sessionid, cid, operation, '', '', dbname)
            else:
                return endsentences(cmpid, serviceid, sessionid, cid, operation, '2', '13', session_data,
                                    session_sort, userid, dbname)
    # 打断忽略

    if operation == '5':
        if text == '':
            tupledata = ('打断忽略', 1, 3, '0', 'open', askid, '', '', '4', '1', '', '', wordslotid, '', '', '4', '1',
                         session_data, session_sort)  # 557788
            return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)
        backlose = mongorobot.getlosejudge(cmpid, text, cid, serviceid)
        web_logger.info('cid:%s backlose:%s', cid, backlose)
        if backlose != "" and str(backlose) == '13':
            tupledata = (
                '打断忽略', 1, 3, '0', 'open', askid, '', '', '4', '1', '', '', wordslotid, '', '', '4', '1',
                session_data, session_sort)  # 557788
            return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)

    # not_word流程
    if text == "" and operation != '4':
        if operation != '14':
            tupledata = (
                '杂音忽略', 1, 3, '0', 'open', askid, '', '', '7', '1', '', '', wordslotid, '', '', '4', '6',
                session_data, session_sort)  # 557788
            return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)

        # 转人工失败后的流程
        if operation == '14':
            memcachcon.del_cach(str(dbname) + 'istransfer' + str(cid))
            memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 13)
            # if beforeistransfer!=None:
            # 更新挂机原因0无人接听 1号码错误 2占线 3接听后挂断 4客户忙碌中稍后联系 5回答超时挂机 6多次拒绝挂机  7邀约拒绝  8脏话 9已转人工 10邀约成功 11用户关机 12防骚扰 13转接失败
            # memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 13)
            # 转接失败，走客服不在线流程
            offline = selcommon(cmpid, serviceid, 1, 'offline', dbname, cid)
            if len(offline) != 0:
                back = globalvariable(offline[0][0], offline[0][1], offline[0][2], offline[0][3], cid, cmpid,
                                      serviceid,
                                      askid, 'offline', '', offline[0][4], offline[0][5], offline[0][6],
                                      session_data,
                                      session_sort, userid, dbname)
                if back != None and len(back) != 0:
                    return recordbackdataforquestion(4, back, sessionid, cid, operation, '', '', dbname)
                    # return back
        # -----------------------------------------以下流程目前已不用----------------------------------------------------------------------------
        # 判断上个流程是否是挂断
        closecountdata = memcachcon.if_exist(str(dbname) + 'closecount' + str(cid))
        print('不用流程走了吗---------------------------------------------------')
        if closecountdata != None:
            # bye = selcommon(cmpid,serviceid,closecount[str(cid)],'bye')
            bye = selcommon(cmpid, serviceid, closecountdata, 'bye', dbname, cid)

            if len(bye) != 0:
                back = globalvariable(bye[0][0], bye[0][1], bye[0][2], bye[0][3], cid, cmpid, serviceid, askid,
                                      'bye', wordslotid, bye[0][4], bye[0][5], bye[0][6], session_data,
                                      session_sort, userid, dbname)
                if back != None and len(back) != 0:
                    return recordbackdataforquestion(len(back), back, sessionid, cid, operation, '0', '',
                                                     dbname)
        if memcachcon.if_exist(str(dbname) + 'cach' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'cach' + str(cid))

        textnullnumdata = memcachcon.if_exist(str(dbname) + 'textnullnum' + str(cid))
        if textnullnumdata == None:
            memcachcon.set_cach(str(dbname) + 'textnullnum' + str(cid), '1')
        else:
            memcachcon.add_num(str(dbname) + 'textnullnum' + str(cid))

        if memcachcon.if_exist(str(dbname) + 'textnull' + str(cid)) == None:
            memcachcon.set_cach(str(dbname) + 'textnull' + str(cid), '1')
        elif memcachcon.if_exist(str(dbname) + 'textnull' + str(cid)) == '1':
            memcachcon.del_cach(str(dbname) + 'textnull' + str(cid))
            if memcachcon.if_exist(str(dbname) + 'textnullnum' + str(cid)) != None:
                memcachcon.del_cach(str(dbname) + 'textnullnum' + str(cid))

            memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 5)
            if memcachcon.if_exist(str(dbname) + 'have_voiced' + str(cid)) == None:
                memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 25)
            return endsentences(cmpid, serviceid, sessionid, cid, operation, '2', '1', session_data,
                                session_sort, userid, dbname)

        textnullnumdata = memcachcon.if_exist(str(dbname) + 'textnullnum' + str(cid))

        if textnullnumdata == None:
            textnullnumdata = '1'

        no_work = selcommon(cmpid, serviceid, textnullnumdata, 'no_word', dbname, cid)

        if len(no_work) != 0:

            back = globalvariable(no_work[0][0], no_work[0][1], no_work[0][2], no_work[0][3], cid, cmpid,
                                  serviceid, askid, 'no_word', wordslotid, no_work[0][4], no_work[0][5],
                                  no_work[0][6], session_data, session_sort, userid, dbname)
            if back != None and len(back) != 0:
                return recordbackdataforquestion(4, back, sessionid, cid, operation, '2', '1', dbname)
            else:

                memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 5)
                if memcachcon.if_exist(str(dbname) + 'have_voiced' + str(cid)) == None:
                    memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 25)
                return endsentences(cmpid, serviceid, sessionid, cid, operation, '2', '1', session_data,
                                    session_sort, userid, dbname)
        else:

            memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 5)
            if memcachcon.if_exist(str(dbname) + 'have_voiced' + str(cid)) == None:
                memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 25)
            return endsentences(cmpid, serviceid, sessionid, cid, operation, '2', '1', session_data,
                                session_sort, userid, dbname)
    # ------------------------------------------------------------------------------------------------------------------------------
    if str(text) != '':

        # 匹配问卷
        questionnairetype = memcachcon.if_exist(str(conn.basedbname) + 'questionnairetype' + askid + str(cid))
        matchidlist = memcachcon.if_exist(str(conn.basedbname) + 'matchidlist' + askid + str(cid))
        if questionnairetype and matchidlist:
            globle_match(serviceid, dbname, cid, text, session_data, session_sort, 2, askid, matchidlist,
                         questionnairetype)

        # 匹配并记录标签
        globle_attirds(serviceid, dbname, cid, text, session_data, session_sort, 1)
        # 记录热词
        hotword = ThreadWithReturnValue(target=sel_hot_word, args=(text, cid, dbname))
        hotword.start()
        # 判断是否脏话
        specail = dirt_txt_back(text, cmpid, serviceid, cid, sessionid, operation, askid, session_data,
                                session_sort, userid, dbname)

        # print('specail',specail)
        if specail != None:
            return specail
    # ------------------------
    # 久不应答后的流程跳转
    if memcachcon.if_exist(str(dbname) + 'cache' + str(cid)) != None and operation != '4':
        web_logger.info('久不应答后 cid:%s operation:%s cmpid:%s askid:%s text:%s', cid, operation, cmpid, askid, text)
        memcachcon.del_cach(str(dbname) + 'cache' + str(cid))
        if operation == '3' and str(askid) != "":
            # 判断是否意图
            data = jugeintention(text, cmpid, cid, serviceid, sessionid, '', askid, '', '', session_data,
                                 session_sort, dbname)  # 查询意图

            if data != None:
                return recordbackdataforquestion(len(data), data, sessionid, cid, operation, '', '', dbname)
            # 问卷
            question_back = question_back_type(cid, sessionid, operation, askid, wordslotid, session_data,
                                               session_sort, dbname)
            ans = mongorobot.getanwservice(cmpid, text, cid, serviceid, askid, operation, robotdata[0],
                                           session_data, session_sort, dbname)
            if ans != 'attitude6' and ans != "attitude7" and ans != "attitude11":
                if question_back != "" and question_back[0] == '{':
                    return question_back
                elif question_back != "":
                    ans = question_back
            web_logger.info('not_input后的匹配 cid:%s operation:%s cmpid:%s askid:%s text:%s question_back:%s ans:%s', cid,
                            operation, cmpid, askid, text, question_back, ans)
            # 判断是否问题库的问题
            if ans != '不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?' and ans[:1] == 'A':
                back = Jumptheanswer(ans, cid, cmpid, askid, serviceid, sessionid, operation, session_data,
                                     session_sort, userid, dbname)
                if back != None and type(back) != str and len(back) != 0:
                    return recordbackdataforquestion(len(back), back, sessionid, cid, operation, '', '', dbname)
                elif type(back) == str and back != None and len(back) != 0:
                    return back

            # HoodleMobile = selHoodleMobileadressinterrupt(askid)
            # #插入调用记录
            # insertask(cmpid,HoodleMobile[0][1],cid,HoodleMobile[0][3],session_data,session_sort)
            # #插入场景
            # insertsessionsence(cid,HoodleMobile[0][3],session_data,session_sort)
            # return recordbackdataforquestion(4,skipquestion(HoodleMobile,cid,'','',cmpid,ans[8:],session_data,session_sort),sessionid,cid,operation,'','')
            # 存在意图没有匹配到问题库的时候
            intentionback = selnotquestionaskintention(cid, askid, sessionid, operation, cmpid, session_data,
                                                       session_sort, dbname)
            if intentionback != None:
                return recordbackdataforquestion(4, intentionback, sessionid, cid, operation, '', '', dbname)
            if ans[:-1] == 'attitude' or ans[:-2] == 'attitude':
                back = allattitude(ans, cid, serviceid, sessionid, operation, askid, cmpid, wordslotid,
                                   session_data, session_sort, userid, dbname)

                web_logger.info('cid:%s operation:%s cmpid:%s askid:%s text:%s back:%s ans:%s',
                                cid, operation, cmpid, askid, text, back, ans)
                if back != None and type(back) != str and len(back) != 0:

                    return recordbackdataforquestion(len(back), back, sessionid, cid, operation, '', '', dbname)
                elif back != None and type(back) == str and len(back) != 0:

                    return back

            if ans[:-1] == 'skill':
                skill = skillskip(ans[5:], '', cid, askid, session_data, session_sort, dbname)

                if skill != None and len(skill) != 0:
                    return recordbackdataforquestion(4, skill, sessionid, cid, operation, '', '', dbname)
            if memcachcon.if_exist(str(dbname) + 'Jumpprocesses' + str(cid)) != None:
                ans = 'notnext'
                web_logger.info('存在跳转问题，已经记录跳转编码 cid:%s operation:%s cmpid:%s askid:%s text:%s  ans:%s',
                                cid, operation, cmpid, askid, text, ans)
                Jumpprocessesnum = memcachcon.if_exist(str(dbname) + 'Jumpprocesses' + str(cid))
                memcachcon.del_cach(str(dbname) + 'Jumpprocesses' + str(cid))
                return juntohoodel(Jumpprocessesnum, cid, sessionid, operation, cmpid, 4, 5, session_data,
                                   session_sort, userid, dbname)
            closecountdata = memcachcon.if_exist(str(dbname) + 'closecount' + str(cid))

            if closecountdata != None:
                bye = selcommon(cmpid, serviceid, closecountdata, 'bye', dbname, cid)
                if len(bye) != 0:
                    back = globalvariable(bye[0][0], bye[0][1], bye[0][2], bye[0][3], cid, cmpid, serviceid,
                                          askid, 'bye', '', bye[0][4], bye[0][5], bye[0][6], session_data,
                                          session_sort, userid, dbname)
                    if back != None and len(back) != 0:
                        return recordbackdataforquestion(len(back), back, sessionid, cid, operation, '0', '',
                                                         dbname)
            web_logger.info('久不应答没有匹配到问题库 ，继续流 cid:%s operation:%s cmpid:%s askid:%s text:%s  ans:%s',
                            cid, operation, cmpid, askid, text, ans)
            nex = haveattitude(cid, 'attitude5', cmpid, askid, serviceid, operation, wordslotid, sessionid,
                               session_data, session_sort, userid, dbname)
            if nex != None:
                return recordbackdataforquestion(4, nex, sessionid, cid, operation, '', '', dbname)
            content = continueline(cid, cmpid, serviceid, askid, '4', session_data, session_sort, '2', userid,
                                   dbname)
            if content != None:
                return recordbackdataforquestion(4, content, sessionid, cid, operation, '', '', dbname)
            else:
                return endsentences(cmpid, serviceid, sessionid, cid, operation, '4', '2', session_data,
                                    session_sort, userid, dbname)

    if operation == '4':
        web_logger.info(' cid:%s operation:%s cmpid:%s askid:%s text:%s', cid, operation, cmpid, askid, text)
        if memcachcon.if_exist(str(dbname) + 'handover' + str(cid)) != None:
            endsentences(cmpid, serviceid, sessionid, cid, operation, '1', '17', session_data, session_sort,
                         userid, dbname)
        closecountdata = memcachcon.if_exist(str(dbname) + 'closecount' + str(cid))
        if closecountdata != None:
            bye = selcommon(cmpid, serviceid, closecountdata, 'bye', dbname, cid)
            if len(bye) != 0:
                back = globalvariable(bye[0][0], bye[0][1], bye[0][2], bye[0][3], cid, cmpid, serviceid, askid,
                                      'bye', wordslotid, bye[0][4], bye[0][5], bye[0][6], session_data,
                                      session_sort, userid, dbname)
                if back != None and len(back) != 0:
                    return recordbackdataforquestion(len(back), back, sessionid, cid, operation, '0', '',
                                                     dbname)
        # 查询是否有静音配置
        mute_count = mute_attitude(askid, dbname, cid)
        if mute_count > 0:
            back = allattitude('attitude14', cid, serviceid, sessionid, operation, askid, cmpid, wordslotid,
                               session_data, session_sort, userid, dbname)

            if back != None and type(back) != str and len(back) != 0:
                return recordbackdataforquestion(len(back), back, sessionid, cid, operation, '1', '14', dbname)

        back = notspearkword(cmpid, serviceid, sessionid, cid, operation, askid, session_data, session_sort,
                             userid, dbname)  # 久不应答
        if back != None and len(back) != 0:
            return back
    else:
        return callrobotphone(cmpid, text, sessionid, cid, choiceback, location, channelid, serviceid, askid,
                              operation, robotdata[0], wordslotid, session_data, session_sort, userid, dbname,
                              originalcmpid, get_digits)


# 判断是否属于全局标签
def globle_attirds(serviceid, dbname, cid, text, session_data, session_sort, type):
    # 查询公司全局标签
    attridsdict = sel_cmpid_attirds(serviceid, dbname, cid, type, '')
    for attrids in attridsdict:
        try:
            regwords = attrids['regwords'].replace(",", "|")
            pipe_word = re.compile(regwords)
            worklist = re.findall(pipe_word, text)
            # 匹配上正则后存储客户标签
            if worklist:
                web_logger.info('cid:%s text:%s worklist:%s', cid, text, worklist)
                tmcustid = seltmcustid(cid, dbname)  # 通过会话编码查到t.tmcustid
                attridlist = str(attrids['attrids']).split(',')
                for attrid in attridlist:
                    insert_zt_customer_attr_link(tmcustid, cid, session_data, session_sort,
                                                 attrid, dbname)
        except Exception as e:
            web_logger.warning('cid:%s attrids:%s  error:%s %s', cid, attrids, type(e), e)


# 判断是否属于问卷
def globle_match(serviceid, dbname, cid, text, session_data, session_sort, type, askid, matchidlist, questionnairetype):
    # 查询公司全局标签
    attridsdict = sel_cmpid_attirds(serviceid, dbname, cid, type, matchidlist)
    web_logger.info('久不应答没有匹配到问题库 ，继续流程 cid:%s serviceid:%s askid:%s text:%s attridsdict:%s', cid, serviceid,
                    askid, text, attridsdict)
    the_match = []
    for attrids in attridsdict:
        try:
            regwords = attrids['regwords'].replace(",", "|")
            pipe_word = re.compile(regwords)
            worklist = re.findall(pipe_word, text)
            # 匹配上正则后存储客户标签
            web_logger.info('cid:%s serviceid:%s askid:%s text:%s regwords:%s worklist:%s attrids:%s',
                            cid, serviceid, askid, text, regwords, worklist, attrids)
            if worklist:
                the_match.append(attrids['matchid'])  # 记录匹配的问卷编码
                tmcustid = seltmcustid(cid, dbname)  # 通过会话编码查到t.tmcustid
                insert_zt_customer_attr_link_match(tmcustid, cid, askid, session_data, session_sort,
                                                   attrids['matchid'], dbname)
        except Exception as e:
            web_logger.warning('cid:%s regwords:%s  error:%s %s', cid, attrids['regwords'], type(e), e)

        have_matchidlist = memcachcon.if_exist(str(conn.basedbname) + 'have_matchidlist' + str(cid))
        if have_matchidlist == None and len(the_match) != 0:
            memcachcon.set_cach(str(conn.basedbname) + 'have_matchidlist' + str(cid), the_match)

        elif len(the_match) != 0:
            have_matchidlist.append(the_match)
            memcachcon.set_cach(str(conn.basedbname) + 'have_matchidlist' + str(cid), have_matchidlist)

        have_matchidlist_askid = memcachcon.if_exist(
            str(conn.basedbname) + 'have_matchidlist_askid' + str(askid) + str(cid))
        if have_matchidlist_askid == None and len(the_match) != 0:
            memcachcon.set_cach(str(conn.basedbname) + 'have_matchidlist_askid' + str(askid) + str(cid), the_match)
        elif len(the_match) != 0:
            have_matchidlist_askid = have_matchidlist_askid + the_match
            # have_matchidlist_askid.append(the_match)
            memcachcon.set_cach(str(conn.basedbname) + 'have_matchidlist_askid' + str(askid) + str(cid),
                                have_matchidlist_askid)


# 查询公司全局标签
def sel_cmpid_attirds(serviceid, dbname, cid, type, matchidlist):
    sql = "SELECT m.attrids,m.regwords,m.matchid from zt_know_global_match m where m.serviceid=" + str(
        serviceid) + " and m.type='" + str(type) + "'  "
    if matchidlist != "":
        sql += " and  m.matchid in (" + str(matchidlist) + ")"
    attridsdict = conn.mysql_seldic(sql, dbname, cid)
    # print(attridsdict)
    return attridsdict


# 跳到指定流程
@time_statistic(1, 'cid')
def juntohoodel(askid, cid, sessionid, operation, cmpid, type, num, session_data, session_sort, userid, dbname):
    HoodleMobile = selHoodleMobileadress(askid, dbname, cid)
    # h.HoodleMobileadress,h.sceneid,h.type,h.qtype,h.remark,interrupt,h.voxfile
    web_logger.info('跳转到指定流程 cid:%s operation askid:%s operation:%s '
                    'HoodleMobileadress:%s sceneid:%s type:%s qtype:%s remark:%s interrupt:%s voxfile:%s', cid, operation, askid, operation, *HoodleMobile)
    ifclose = "open"
    # 插入调用记录
    insertask(cmpid, askid, cid, HoodleMobile[0][1], session_data, session_sort, dbname)
    if str(HoodleMobile[0][1]) == str(4):
        ifclose = 'close'
    backchangedata = changebackdataforTTS(HoodleMobile[0][3], HoodleMobile[0][2], HoodleMobile[0][0],
                                          HoodleMobile[0][4], HoodleMobile[0][6], cmpid, userid, cid, dbname)

    tupledata = (
        backchangedata['backtext'], backchangedata['backtype'], 1, '0', ifclose, askid, '', '', '',
        backchangedata['backremark'], '', HoodleMobile[0][5], '',
        '', '', type, num, session_data, session_sort)  # 557788
    return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)


# 调用接口返回文本
def invokingurltext(urltext):
    try:
        req = rs.get(urltext)
        data = req.text
        return data
    except:
        return '调用api接口出错！'


# 调用接口返回json
def invokingurljson(urltext, cid):
    try:
        web_logger.info('cid:%s urltext:%s', cid, urltext)
        req = rs.get(urltext, timeout=1)
        elapsedendtime = req.elapsed
        data = req.json()
        web_logger.info('cid:%s urltext:%s data:%s elapsedendtime:%s', cid, urltext, data, elapsedendtime)
        return data
    except Exception as e:
        web_logger.warning('接口调用错误 cid:%s error:%s %s', cid, type(e), e)
        return {'err!!': '调用api接口出错！!'}


# 调用接口返回json
def invokingurljson_post(cid, adress, phone):
    try:

        the_sig_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        id = "N00000052307"
        apis = "0cfe5870-fee6-11ea-acb2-d19ca7543771"
        sig = hashlib.md5(str(id + apis + the_sig_time).encode()).hexdigest().upper()
        the_au = str(id) + ":" + str(the_sig_time)
        host = "https://apis.7moor.com/v20170704/business/handleBusiness/N00000052307?sig=" + str(sig) + ""
        # 设置HTTP请求头部
        the_date = datetime.datetime.now()
        datas = {
            '_id': str(the_date),
            'number': str(the_date),
            'uniqueId': str(the_date),
            "customerId": '',
            "fields": [
                {"name": "报障电话", "type": "single", "value": str(phone)},
                {"name": "报障地址", "type": "single", "value": str(adress)},
                {"name": "时间", "type": "single", "value": str(the_date.strftime('%Y-%m-%d'))},  # %H:%M:%S'
            ],
            "targetUser": '8001',
            "createUser": "8000",
            "flowName": "故障申报工单",
            "comment": "",
            "stepName": "开始步骤",
            "action": "处理",
            "priority": "1",
        }
        web_logger.info('cid:%s host:%s', cid, host)
        headers = {'Content-Type': 'application/json', "authorization": str(base64.b64encode(the_au.encode()).decode())}
        datas = json.dumps(datas)
        req = rs.post(host, data=datas, headers=headers)
        the_json = req.json()
        web_logger.info('cid:%s response:%s req:%s the_json:%s', cid, datas.encode('utf-8').decode('unicode_escape'),
                        req, the_json)
        return the_json
    except Exception as e:
        weixin_push(str(cid), str(e), '意图定制调用api接口出错！!')
        web_logger.warning('调用api接口出错 cid:%s error:%s %s', cid, type(e), e)
        return {'err!!': '调用api接口出错！!'}


# 久不应答
@time_statistic(3, 'cid')
def notspearkword(cmpid, serviceid, sessionid, cid, operation, askid, session_data, session_sort, userid, dbname):
    nospeakcachedata = memcachcon.if_exist(str(dbname) + 'nospeakcache' + str(cid))
    # print('nospeakcachedata',nospeakcachedata)
    if nospeakcachedata == None:  # 久不应答回答内容排序
        memcachcon.set_cach(str(dbname) + 'nospeakcache' + str(cid), 1)
    else:
        memcachcon.add_num(str(dbname) + 'nospeakcache' + str(cid))
    cachedata = memcachcon.if_exist(str(dbname) + 'cache' + str(cid))
    web_logger.info('久答不应 cid:%s serviceid:%s cmpid:%s operation:%s askid:%s cachedata:%s', cid, serviceid, cmpid,
                    operation, askid, cachedata)
    if cachedata == None:
        memcachcon.set_cach(str(dbname) + 'cache' + str(cid), '1')
    elif str(cachedata) == '1':
        memcachcon.del_cach(str(dbname) + 'cache' + str(cid))
        # 更新挂机原因
        memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 5)
        if memcachcon.if_exist(str(dbname) + 'have_voiced' + str(cid)) == None:
            memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 25)
        return endsentences(cmpid, serviceid, sessionid, cid, operation, '2', '3', session_data, session_sort, userid,
                            dbname)
    if memcachcon.if_exist(str(dbname) + 'answercach' + str(cid)) != None:  # 删除之前的缓存
        memcachcon.del_cach(str(dbname) + 'answercach' + str(cid))
    if nospeakcachedata == None:
        nospeakcachedata = 1
    else:
        nospeakcachedata = int(nospeakcachedata) + 1
    no_input = selcommon(cmpid, serviceid, nospeakcachedata, 'no_input', dbname, cid)  #
    if len(no_input) != 0:
        back = globalvariable(no_input[0][0], no_input[0][1], no_input[0][2], no_input[0][3], cid, cmpid, serviceid,
                              askid, 'no_input', '', no_input[0][4], no_input[0][5], no_input[0][6], session_data,
                              session_sort, userid, dbname)
        if back != None and len(back) != 0:
            return recordbackdataforquestion(4, back, sessionid, cid, operation, '', '', dbname)
        else:
            # 更新挂机原因
            memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 5)
            if memcachcon.if_exist(str(dbname) + 'have_voiced' + str(cid)) == None:
                memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 25)

            return endsentences(cmpid, serviceid, sessionid, cid, operation, '2', '3', session_data, session_sort,
                                userid, dbname)
    else:
        # 更新挂机原因
        memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 5)
        if memcachcon.if_exist(str(dbname) + 'have_voiced' + str(cid)) == None:
            memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 25)
        return endsentences(cmpid, serviceid, sessionid, cid, operation, '2', '3', session_data, session_sort, userid,
                            dbname)


@time_statistic(2, 'cid')
def specailanswerattitue(cmpid, serviceid, cid, sessionid, operation, askid, attitue, session_data, session_sort,
                         userid, dbname):
    notnone = ()
    web_logger.info('cid:%s serviceid:%s cmpid:%s operation:%s askid:%s attitue:%s', cid, serviceid, cmpid, operation,
                    askid, attitue)
    if str(attitue) == '6':

        if memcachcon.if_exist(str(dbname) + 'nottime' + str(cid)) == None:
            memcachcon.set_cach(str(dbname) + 'nottime' + str(cid), 1)
        else:
            memcachcon.add_num(str(dbname) + 'nottime' + str(cid))

        nottimedata = memcachcon.if_exist(str(dbname) + 'nottime' + str(cid))
        if nottimedata == None:
            nottimedata = '1'
        busy = selcommon(cmpid, serviceid, nottimedata, 'busy', dbname, cid)

        if len(busy) != 0:
            back = globalvariable(busy[0][0], busy[0][1], busy[0][2], busy[0][3], cid, cmpid, serviceid, askid, 'busy',
                                  '', busy[0][4], busy[0][5], busy[0][6], session_data, session_sort, userid, dbname)
            if back != None and len(back) != 0:
                notnone = back

    # 重复一遍

    elif str(attitue) == '7':

        if memcachcon.if_exist(str(dbname) + 'comeagain' + str(cid)) == None:
            memcachcon.set_cach(str(dbname) + 'comeagain' + str(cid), 1)

        else:
            memcachcon.add_num(str(dbname) + 'comeagain' + str(cid))

        comeagaindata = memcachcon.if_exist(str(dbname) + 'comeagain' + str(cid))
        if comeagaindata == 3:

            repeat = selcommon(cmpid, serviceid, comeagaindata, 'repeat', dbname, cid)  #

            if len(repeat) != 0:
                back = globalvariable(repeat[0][0], repeat[0][1], repeat[0][2], repeat[0][3], cid, cmpid, serviceid,
                                      askid, 'repeat', '', repeat[0][4], repeat[0][5], repeat[0][6], session_data,
                                      session_sort, userid, dbname)
                if back != None and len(back) != 0:
                    notnone = back
        else:
            answerid = selfinallyanswer(cid, session_data, dbname)
            web_logger.info('cid:%s serviceid:%s cmpid:%s operation:%s askid:%s answerid:%s', cid, serviceid, cmpid,
                            operation, askid, answerid)
            if str(answerid) != '0':
                notnone = backattachdata(cid, answerid, askid, cmpid, serviceid, sessionid, operation, session_data,
                                         session_sort, userid, dbname)
            else:
                HoodleMobile = selHoodleMobileadressinterrupt(askid, dbname, cid)

                if len(HoodleMobile) != 0:
                    back = skipquestion(HoodleMobile, cid, '', 'repeat', cmpid, '', session_data, session_sort, userid,
                                        dbname)
                    if back != None and len(back) != 0:
                        notnone = back
    elif str(attitue) == '11':

        if memcachcon.if_exist(str(dbname) + 'await' + str(cid)) == None:
            memcachcon.set_cach(str(dbname) + 'await' + str(cid), 1)

        else:
            memcachcon.add_num(str(dbname) + 'await' + str(cid))

        awaitdata = memcachcon.if_exist(str(dbname) + 'await' + str(cid))
        if awaitdata == None:
            awaitdata = '1'
        wait = selcommon(cmpid, serviceid, awaitdata, 'await', dbname, cid)
        if len(wait) != 0:
            back = globalvariable(wait[0][0], wait[0][1], wait[0][2], wait[0][3], cid, cmpid, serviceid, askid, 'await',
                                  '', wait[0][4], wait[0][5], wait[0][6], session_data, session_sort, userid, dbname)
            if back != None and len(back) != 0:
                notnone = back
    if notnone != ():
        return recordbackdataforquestion(4, notnone, sessionid, cid, operation, '', '', dbname)


#
# # 忙碌，脏话，重复一遍
# def specialback(text, cmpid, serviceid, cid, sessionid, operation, askid, session_data, session_sort, userid, dbname):
#     # 判断是否忙碌
#
#     notnone = ()
#     # 脏话
#     global baiduapitoken
#     if notnone == ():
#         try:
#
#             writetxt('robottxt', '脏话开始   ' + str(cid) + str(datetime.datetime.now()))
#             urllink = 'https://aip.baidubce.com/rest/2.0/antispam/v2/spam?access_token=' + str(baiduapitoken)
#             boby = {'content': str(text)}
#             req = rs.post(urllink, data=boby, timeout=3)
#             # req = rs.post(urllink, timeout=60)
#
#             data = req.json()
#             # print('data',data)
#             req.close()
#             if 'error_code' in data.keys():
#
#                 writetxt('error_code', 'in 会话编码:' + str(cid) + ' ' + str(datetime.datetime.now()) + ' ' + str(text) +
#                          ' error_code: ' + str(data)
#                          )
#                 if str(data['error_code']) == '111' or str(data['error_code']) == '110':
#                     # apitaken = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=9goGmAIOyCEEGjF8edHO9Syu&client_secret=z5cOOdIys39Y7zV9CNiGoYkWDyGlQuzZ'
#                     apitaken = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=wVijsc3uL8R0hWvc8nK3SbAK&client_secret=hMt8Ij0i0xAy85o8vYTf4O0FdSRA6kYe'
#                     req = rs.post(apitaken)
#                     apidata = req.json()
#                     # print('apidata',apidata)
#
#                     if 'access_token' in apidata.keys():
#                         baiduapitoken = apidata['access_token']
#             if str(data['result']['spam']) == '1':
#                 if memcachcon.if_exist(str(dbname) + 'profanity' + str(cid)) == None:
#                     memcachcon.set_cach(str(dbname) + 'profanity' + str(cid), 1)
#                 else:
#                     memcachcon.add_num(str(dbname) + 'profanity' + str(cid))
#
#                 profanitydata = memcachcon.if_exist(str(dbname) + 'profanity' + str(cid))
#                 if profanitydata == None:
#                     profanitydata = 1
#
#                 profanitydata = selcommon(cmpid, serviceid, profanitydata, 'dirty', dbname, cid)
#                 if len(profanitydata) != 0:
#                     back = globalvariable(profanitydata[0][0], profanitydata[0][1], profanitydata[0][2],
#                                           profanitydata[0][3], cid, cmpid, serviceid, askid, 'dirty', '',
#                                           profanitydata[0][4], profanitydata[0][5], profanitydata[0][6], session_data,
#                                           session_sort, userid, dbname)
#                     if back != None and len(back) != 0:
#                         notnone = back
#             writetxt('robottxt', '脏话结束   ' + str(cid) + str(datetime.datetime.now()))
#
#         except Exception as e:
#             web_logger.warning('cid:%s  text:%s  error:%s %s', cid, text, type(e), e)
#
#     if notnone != ():
#         return recordbackdataforquestion(4, notnone, sessionid, cid, operation, '', '', dbname)


def get_dirt_txt(dbname, cid):
    dirtylist = get_dirty_sql(dbname, cid)
    dirt_txt_data = []
    dirt_txt_data_str = ''
    for dirty in dirtylist:
        line = dirty[0]
        if line != "":
            word = str(line).replace('\n', '')
            dirt_txt_data.append(word)
            dirt_txt_data_str += str(word) + '|'

    if dirt_txt_data_str != "":
        dirt_txt_data_str = dirt_txt_data_str[:-1]

    memcachcon.set_cach_not_time('dirt_txt_data_str', dirt_txt_data_str)
    memcachcon.set_cach_not_time('dirt_txt_data', dirt_txt_data)
    web_logger.debug('DIRTY:%s', dirt_txt_data)


get_dirt_txt('', '')


def add_dirt_txt(text, dbname, cid):
    try:
        dirt_txt_data = memcachcon.if_exist('dirt_txt_data')
        web_logger.debug('text:%s DIRTY:%s', text, dirt_txt_data)
        if text not in dirt_txt_data:
            if dirt_txt_data != None:
                dirt_txt_data_str = memcachcon.if_exist('dirt_txt_data_str')
                memcachcon.set_cach_not_time('dirt_txt_data_str', dirt_txt_data_str + '|' + str(text))
                memcachcon.set_cach_not_time('dirt_txt_data', dirt_txt_data + [str(text)])
            else:
                memcachcon.set_cach_not_time('dirt_txt_data_str', str(text))
                memcachcon.set_cach_not_time('dirt_txt_data', [str(text)])
            insert_dirty_sql(text, dbname, cid)
            return 'true'
        return 'exist'
    except Exception as e:
        web_logger.error('cid:%s text:%s error:%s %s', cid, text, type(e), e)
        return 'false'


def del_dirt_txt(text, dbname, cid):
    try:
        dirt_txt_data = memcachcon.if_exist('dirt_txt_data')
        dirt_txt_data_str = memcachcon.if_exist('dirt_txt_data_str')
        if text in dirt_txt_data:
            del_dirty_sql(text, dbname, cid)
            dirt_txt_data_str.replace('|' + str(text), '')
            dirt_txt_data.remove(str(text))
            memcachcon.set_cach_not_time('dirt_txt_data_str', dirt_txt_data_str)
            memcachcon.set_cach_not_time('dirt_txt_data', dirt_txt_data)

        return 'true'

    except Exception as e:
        web_logger.error('cid:%s text:%s error:%s %s', cid, text, type(e), e)
        return 'false'


def sel_dirt_txt(text, pagesize, page, time, dbname, cid):
    try:
        dirtylist = sel_dirty_sql(text, pagesize, page, time, dbname, cid)
        backtuple = {'code': str(1), 'dirtylist': dirtylist}
        backcon = json.dumps(backtuple, ensure_ascii=False)
        return backcon

    except Exception as e:
        web_logger.error('cid:%s text:%s error:%s %s', cid, text, type(e), e)
        backtuple = {'code': str(-1), 'dirtylist': []}
        backcon = json.dumps(backtuple, ensure_ascii=False)
        return backcon


def sel_dirt_txt_count(text, time, dbname, cid):
    try:
        dirtyconut = sel_dirty_sql_count(text, time, dbname, cid)
        backtuple = {'code': str(1), 'dirtyconut': dirtyconut}
        backcon = json.dumps(backtuple, ensure_ascii=False)
        return backcon

    except Exception as e:
        web_logger.error('cid:%s text:%s error:%s %s', cid, text, type(e), e)
        backtuple = {'code': str(-1), 'dirtylist': 0}
        backcon = json.dumps(backtuple, ensure_ascii=False)
        return backcon


def dirt_txt_back(text, cmpid, serviceid, cid, sessionid, operation, askid, session_data, session_sort, userid, dbname):
    # 判断是否忙碌

    notnone = ()
    # 脏话

    try:
        web_logger.info('开始匹配脏话 cid:%s ', cid)
        dirt_txt_data_str = memcachcon.if_exist('dirt_txt_data_str')
        if dirt_txt_data_str:
            pipe_word = re.compile(dirt_txt_data_str)
            worklist = re.findall(pipe_word, text)
            if len(worklist) != 0:
                if memcachcon.if_exist(str(dbname) + 'profanity' + str(cid)) == None:
                    memcachcon.set_cach(str(dbname) + 'profanity' + str(cid), 1)
                else:
                    memcachcon.add_num(str(dbname) + 'profanity' + str(cid))

                profanitydata = memcachcon.if_exist(str(dbname) + 'profanity' + str(cid))
                if profanitydata == None:
                    profanitydata = 1

                profanitydata = selcommon(cmpid, serviceid, profanitydata, 'dirty', dbname, cid)
                if len(profanitydata) != 0:
                    back = globalvariable(profanitydata[0][0], profanitydata[0][1], profanitydata[0][2],
                                          profanitydata[0][3], cid, cmpid, serviceid, askid, 'dirty', '',
                                          profanitydata[0][4], profanitydata[0][5], profanitydata[0][6], session_data,
                                          session_sort, userid, dbname)
                    if back != None and len(back) != 0:
                        notnone = back
            web_logger.info('匹配脏话结束 cid:%s ', cid)
    except Exception as e:
        web_logger.warning('cid:%s  text:%s  error:%s %s', cid, text, type(e), e)

    if notnone != ():
        return recordbackdataforquestion(4, notnone, sessionid, cid, operation, '', '', dbname)


# 全局跳转
@time_statistic(4, 'cid')
def globalvariable(content, ctype, text, type, cid, cmpid, serviceid, askid, attituescence, wordslotid, intentionid,
                   isend, voxfile, session_data, session_sort, userid, dbname):
    # ctype：1文字 2语音 3预生成录音
    # type 1问题跳转 2场景跳转 3转人工 4发短信 5回答 6流程继续 7转号码
    web_logger.info('cid:%s serviceid:%s cmpid:%s askid:%s attituescence:%s type：%s', cid, serviceid, cmpid, askid,
                    attituescence, type)
    closeresult = 3
    answerfalg = 1
    nacknum = ''
    if attituescence != "":
        if attituescence == "busy":
            closeresult = 4
        elif attituescence == "no_input" or attituescence == "no_word":
            # print('3333')
            closeresult = 5
            if memcachcon.if_exist(str(dbname) + 'have_voiced' + str(cid)) == None:
                closeresult = 25

        elif attituescence == "refuse":
            closeresult = 6
        elif attituescence == "dirty":
            closeresult = 8
        else:
            closeresult = 3
        if attituescence == "no_match":
            answerfalg = 3

    if attituescence != "":
        if attituescence == "no_word":
            nacknum = 1
        elif attituescence == "no_match":
            nacknum = 2
        elif attituescence == "no_input":
            nacknum = 3
        elif attituescence == "busy":
            nacknum = 4
        elif attituescence == "dirty":
            nacknum = 5
        elif attituescence == "to_much":
            nacknum = 6
        elif attituescence == "repeat":
            nacknum = 7
        elif attituescence == "break":
            nacknum = 8
        elif attituescence == "transform":
            nacknum = 9
        elif attituescence == "send_note":
            nacknum = 10
        elif attituescence == "refuse":
            nacknum = 11
        elif attituescence == "await":
            nacknum = 12
        elif attituescence == "awaken":
            nacknum = 13
        elif attituescence == "hello":
            nacknum = 14
        elif attituescence == "bye":
            nacknum = 15
        elif attituescence == "offline":
            nacknum = 16
        elif attituescence == "handover":
            nacknum = 17
        elif attituescence == "largestword":
            nacknum = 18
        elif attituescence == "question":
            nacknum = 19
        else:
            pass
    if type == 1:  # 问题跳转
        web_logger.info('问题跳转 cid:%s serviceid:%s cmpid:%s askid:%s type：%s', cid, serviceid, cmpid, askid, type)
        HoodleMobile = selHoodleMobileadressinterrupt(content, dbname, cid)
        if len(HoodleMobile) != 0:
            return skipquestion(HoodleMobile, cid, closeresult, attituescence, cmpid, '', session_data, session_sort,
                                userid, dbname)
    elif type == 2:  # 场景跳转
        web_logger.info('场景跳转 cid:%s serviceid:%s cmpid:%s askid:%s type：%s', cid, serviceid, cmpid, askid, type)
        return skipscene(content, cmpid, serviceid, cid, closeresult, attituescence, 2, nacknum, session_data,
                         session_sort, userid, dbname)
    elif type == 3:  # 转人工
        web_logger.info('转人工 cid:%s serviceid:%s cmpid:%s askid:%s type：%s', cid, serviceid, cmpid, askid, type)
        return Turntotheartificial(cmpid, serviceid, content, cid, askid, '2', nacknum, session_data, session_sort,
                                   userid, dbname)
    elif type == 4:  # 发短信
        web_logger.info('发短信 cid:%s serviceid:%s cmpid:%s askid:%s type：%s', cid, serviceid, cmpid, askid, type)
        return sendmessagecommon(cmpid, serviceid, askid, content, cid, '2', nacknum, session_data, session_sort,
                                 userid, dbname)
    elif type == 5:  # 回答
        web_logger.info('回答 cid:%s serviceid:%s cmpid:%s askid:%s type：%s', cid, serviceid, cmpid, askid, type)
        instructid = ''
        if str(attituescence) == "await":
            instructid = '2'
        if intentionid != None:
            intentionrecord_data = memcachcon.if_exist(str(dbname) + 'intentionrecord' + str(cid))
            if intentionrecord_data != None:
                if str(intentionrecord_data) == str(intentionid):
                    backtype = ctype
                    backremark = ''
                    if ctype == 3:
                        backremark = content
                        content = voxfile
                        backtype = 9
                    elif ctype == 2:
                        backtype = 9
                        backremark = text

                    return (content, backtype, answerfalg, '', 'open', askid, '', '', instructid, backremark, '', '',
                            wordslotid, '', '', '', '', session_data, session_sort)  # 557788

            expressionid = selexpretion(intentionid, dbname, cid)
            web_logger.info('意图信息 cid:%s expressionid:%s intentionid：%s', cid, expressionid, intentionid)

            memcachcon.set_cach(str(dbname) + 'nowexpression' + str(cid), expressionid)
            keymainid = install_key_main(cid, expressionid, dbname)
            memcachcon.set_cach(str(dbname) + 'Globalkeymainid' + str(cid), keymainid)
            memcachcon.set_cach(str(dbname) + 'intentionrecord' + str(cid), intentionid)
            grooveid = insalldata(cid, expressionid, intentionid, keymainid, dbname)
            if grooveid != None:
                memcachcon.set_cach(str(dbname) + 'Globalgrooveid' + str(cid), grooveid)

        ifend = 'open'
        if str(isend) == '1':
            ifend = 'close'
        backchangedata = changebackdataforTTS(1, ctype, content, text, voxfile, cmpid, userid, cid, dbname)

        return (
            backchangedata['backtext'], backchangedata['backtype'], answerfalg, '', ifend, askid, '', '', instructid,
            backchangedata['backremark'], '', '', wordslotid, '', '',
            '' if attituescence == '' else '2', nacknum, session_data, session_sort)
    elif type == 7:  # 转号码
        web_logger.info('转号码 cid:%s serviceid:%s cmpid:%s askid:%s type：%s', cid, serviceid, cmpid, askid, type)
        return Turnphone(cmpid, serviceid, content, cid, askid, '2', nacknum, session_data, session_sort, userid,
                         dbname)
    else:  # 流程继续
        HoodleMobile = sellastanswerscen(cid, cmpid, serviceid, askid, dbname)
        web_logger.info('流程继续 cid:%s serviceid:%s cmpid:%s askid:%s type：%s HoodleMobile:%s', cid, serviceid, cmpid,
                        askid, type, HoodleMobile)
        if len(HoodleMobile) != 0:
            return skipquestion(HoodleMobile, cid, closeresult, attituescence, cmpid, '', session_data, session_sort,
                                userid, dbname)


# 查询是否有问题
def selaskfor(cmpid, serviceid, cid, sessionid, operation, session_data, session_sort, userid, dbname):
    # 没有提问关闭操作
    return ifhavaattachdata(cmpid, serviceid, cid, sessionid, operation, session_data, session_sort, userid, dbname)


# 记录查询图片的记录并记录返回结果
def backguidanceinfolist(cid, guidanceinfolistid, dbname):
    return selguidancephoto(cid, guidanceinfolistid, dbname)


# 查找行业术语
def getnewword(cmpid, dbname, cid):
    sql = "select (case when w.newwords='' or w.newwords is null then w.newword else CONCAT(w.newword ,',',w.newwords  ) end ) as words,w.wordSize from zy_robot_word w where w.cmpid='" + str(
        cmpid) + "' "
    newwords = conn.mysql_seldic(sql, dbname, cid)
    return newwords


# 查询全部相关的词
def replaceword(key, dbname, cid):
    sql = "select CONCAT(w.newword,',',w.newwords) from zy_robot_word w where FIND_IN_SET('" + str(
        key) + "',w.newwords) or w.newword like '%" + str(key) + "%'  ORDER BY w.Dtime DESC LIMIT 0,1"
    keyword = conn.mysql_selrowid(sql, dbname, cid)
    backkey = key
    if keyword != None and keyword != 'null' and keyword != '':
        backkey = keyword
    return backkey


# 查询相关的问题
def selkeyword(key, cmpid, dbname, cid):
    where = " and (  "
    where1 = " and (  "
    for keyword in key.split(','):
        where += " kq.question like '%" + keyword + "%' or"
        where1 += " sq.question like '%" + keyword + "%' or"
    where = where[:-2] + " )"
    where1 = where1[:-2] + " )"

    sql = " select  GROUP_CONCAT(a.id) as questionlist from (select kq.question,kq.quesid as id from zt_know_question kq,zt_know_answer ka where  "
    sql += " ka.answerid=kq.answerid and kq.state=1 and kq.cmpid='" + str(cmpid) + "'  " + where + " "
    sql += " union all "
    sql += " SELECT sq.question,kq.quesid as id from zt_know_samequestion sq,zt_know_answer ka ,zt_know_question kq  "
    sql += " where sq.quesid=kq.quesid and ka.answerid=kq.answerid and kq.state=1 and kq.cmpid='" + str(
        cmpid) + "' " + where1 + " ) a   GROUP BY a.id"
    newwordlist = conn.mysql_seldic(sql, dbname, cid)
    return newwordlist


# 返回关键词
def p(text):
    seg_list = list(jieba.cut(text, cut_all=False))
    # ci = " ".join(seg_list)  # 精确模式
    return seg_list


def get_n(text):
    seg_list = jieba.analyse.extract_tags(text, topK=20, withWeight=False, allowPOS=(
        'n', 'nr', 'ns', 'nsf', 'nt', 'nz', 'ng', 'nl', 't', 'tg', 's', 'a', 'al'))
    return seg_list


def sel_hot_word(text, cid, dbname):
    word_list = get_n(text)
    for word in word_list:
        insert_hot_word(word, cid, dbname)


def insert_hot_word(word, scid, dbname):
    sql = "INSERT into zt_ai_hotword(word,scid) VALUES('" + str(word) + "','" + str(scid) + "')"
    conn.mysql_insertid(sql, dbname, scid)


jieba.initialize()


# 返回关键词
def participles(cmpid, text, dbname, cid):
    jieba.initialize()
    newword = getnewword(cmpid, dbname, cid)
    for words in newword:
        for word in str(words['words']).split(','):
            if word != "":
                jieba.add_word(str(word), words['wordSize'])

    key = jieba.analyse.extract_tags(text, topK=1)

    if key != []:
        queslist = selkeyword(replaceword(key[0], dbname, cid), cmpid, dbname, cid)
        if queslist != ():
            return queslist[0]['questionlist']
    return ''


# 查询相关问题信息
def selWithquestion(questionlist, cmpid, dbname, cid):
    sql = " select cast(@rowNO := @rowNo+1 as signed)  AS rowno,q.quesid ,q.question from zt_know_question q,(select @rowNO :=0) b  where FIND_IN_SET(q.quesid ,'" + str(
        questionlist) + "') and q.state=1  and q.cmpid='" + str(cmpid) + "' ORDER BY q.createtime DESC"
    Withquestion = conn.mysql_seldic(sql, dbname, cid)
    return Withquestion


# 查询问题的相关推荐
def correlation(ansid, dbname, cid):
    sql = "  select   cast(@rowNO := @rowNo+1 as signed)  AS rowno,qu.quesid,question from zt_know_question qu,(select @rowNO :=0) b   where "
    sql += " FIND_IN_SET(qu.quesid ,(select q.similarityQuestion from zt_know_answer a,zt_know_question q  where a.answerid='" + str(
        ansid) + "' and q.answerid=a.answerid)) and"
    sql += "    qu.state=1 ORDER BY FIND_IN_SET(qu.quesid ,(select q.similarityQuestion from zt_know_answer a,zt_know_question q  where a.answerid='" + str(
        ansid) + "' and q.answerid=a.answerid))  ;"
    correlationlist = conn.mysql_seldic(sql, dbname, cid)
    return correlationlist


# 查询行业术语
def selnewworkdata(cmpid, selword, pagesize, page, wordid, dbname, cid):
    sql = " select w.wordsid as 词编码, w.newword as 标准词 ,w.newwords as 相似词 ,w.wordSize as 比重,CONCAT(w.Dtime)   as 创建时间 from zy_robot_word w  "
    sql += " where w.cmpid='" + str(cmpid) + "' "
    if selword:
        sql += "  and (w.newword like '%" + str(selword) + "%' or  FIND_IN_SET('" + str(selword) + "',w.newwords))  "
    if wordid:
        sql += " and w.wordsid='" + str(wordid) + "' "
    sql += " GROUP BY w.wordsid ORDER BY w.Dtime desc   "
    if pagesize and page:
        sql += "  LIMIT " + str(int(pagesize) * (int(page) - 1)) + " , " + str(pagesize) + " "
    newwordlist = conn.mysql_seldic(sql, dbname, cid)
    return newwordlist


# 查询行业术语分页
def selnewworkdatapage(cmpid, selword, dbname, cid):
    sql = " select  count(w.wordsid) from zy_robot_word w  "
    sql += " where w.cmpid='" + str(cmpid) + "' "
    if selword:
        sql += "  and (w.newword like '%" + selword + "%' or  FIND_IN_SET('" + str(selword) + "',w.newwords))  "
    newwordcount = conn.mysql_selrowid(sql, dbname, cid)
    return newwordcount


# 查询新词是否已存在
def judgenewword(cmpid, newword, wordid, dbname, cid):
    sql = " select count(w.wordsid) from zy_robot_word w where w.newword='" + str(newword) + "' and w.cmpid='" + str(
        cmpid) + "' "
    if wordid:
        sql += " and w.wordsid!='" + str(wordid) + "' "
    newwordcount = conn.mysql_selrowid(sql, dbname, cid)
    return newwordcount


# 添加新行业术语返回插入条数
def insertnewwords(cmpid, newword, newwords, wordsize, dbname, cid):
    juge = judgenewword(cmpid, newword, "", dbname, cid)
    if juge != 0:
        return 2
    sql = " INSERT into zy_robot_word (newword,newwords,cmpid,wordsize) VALUES "
    sql += " ('" + str(newword) + "','" + str(newwords) + "','" + str(cmpid) + "','" + str(wordsize) + "')"
    insertcount = conn.mysql_insert(sql, dbname, cid)
    return insertcount


# 修改新行业术语返回修改行数
def updatanewwords(cmpid, wordid, newword, newwords, wordsize, dbname, cid):
    juge = judgenewword(cmpid, newword, wordid, dbname, cid)
    if juge != 0:
        return 2
    sql = " update zy_robot_word set newword='" + str(newword) + "' ,newwords='" + str(newwords) + "',wordSize='" + str(
        wordsize) + "',updatadate=NOW() where wordsid='" + str(wordid) + "'"
    insertcount = conn.mysql_updata(sql, dbname, cid)
    return insertcount


# 删除新词
def delnewwordsql(cmpid, wordid, dbname, cid):
    sql = "DELETE from zy_robot_word  where  wordsid='" + str(wordid) + "' and cmpid='" + str(cmpid) + "';"
    delcount = conn.mysql_updata(sql, dbname, cid)
    return delcount


# 添加到机器人的学习
def addrobotlearning(token, quesid, learnquestion, cid, dbname):
    cmpid = getcmpid(str(token), dbname, cid)
    # 判断公司编码是否有效
    if cmpid != '' and cmpid != conn.err:
        sql = " INSERT into zy_robot_learning (createtime,quesid,learnquestion,cmpid,cid) VALUES "
        sql += " (now(),'" + str(quesid) + "','" + str(learnquestion) + "','" + str(cmpid) + "','" + str(cid) + "')"
        insertcount = conn.mysql_insert(sql, dbname, cid)
        return insertcount
    else:
        return str(0)

    # 写入文本记录


# 元组转json
def getJSONString(tuplelist):
    jsonlist = ""
    rs = "{"
    for i in tuplelist:
        rs += jsonlist + '"' + str(i[0]) + '":"' + str(i[1]) + '"'
        jsonlist = ","
    return rs + "}"


# 判断是否配置机器人
def judgeidhaverobot(cmpid, dbname, cid):
    sql = "select count(*) from zt_cmp_robot cr where cr.cmpid=" + str(cmpid) + " ;"
    ifopen = conn.mysql_selrowid(sql, dbname, cid)
    return ifopen


# 判断是否配置机器人
def judgeidhaverobotphone(cmpid, serviceid, dbname, cid):
    sql = "select cr.cmpid,industryid  from zt_cmp_robot cr where cr.cmpid=" + str(
        cmpid) + " and cr.onserviceid = '" + str(serviceid) + "';"
    ifopen = conn.mysql_sel(sql, dbname, cid)
    # print(sql)
    return ifopen


# 判断寒暄是否开启
def judgeapiopen(cmpid, dbname, cid):
    sql = "select cr.smalltalk from zt_cmp_robot cr where cr.cmpid=" + str(cmpid) + " ;"
    ifopen = conn.mysql_selrowid(sql, dbname, cid)
    return ifopen


# 判断token是否正确并返回公司编码
def getcmpid(token, dbname, cid):
    sql = "select cp.COMPANYID from zt_company cp where cp.token='" + token + "' ; "
    cmpid = conn.mysql_selrowid(sql, dbname, cid)
    return cmpid


# 查询公司的常见问题
def comquestion(cmpid, dbname, cid):
    sql = " select kn.sendno,kn.quesid,kn.question from zt_know_question kn  \
      where kn.cmpid=" + str(cmpid) + " and state=1 and kn.sendbyrobot=1 ORDER BY  kn.sendno "
    question = conn.mysql_seldic(sql, dbname, cid)
    return question


# 插入返回数据
def insertbackrecord(sessionid, code, answerFlag, answer, dbname, cid):
    sql = " insert into zy_robotanswer(sessionid,`CODE`,answerflag,Tdata,answer) VALUES \
           (" + str(sessionid) + "," + str(code) + "," + str(answerFlag) + ",NOW()," + json.dumps(answer,
                                                                                                  ensure_ascii=False) + "); "
    execount = conn.mysql_insert(sql, dbname, cid)
    return execount


# 插入调用机器人记录
def insetCallrecords(cid, text, flag, cmpid, channerlid, clevel, location, dbname):
    sql = " insert into zy_rcustomerquestion (cid,contet,questionFlag,cmpid,Tdata,channerlid,clevel,location)"
    sql = sql + " VALUES('" + str(cid) + "'," + json.dumps(text, ensure_ascii=False) + ",'" + str(flag) + "','" + str(
        cmpid) + "',now(),  \
      " + str(channerlid) + "," + str(clevel) + ",'" + str(location) + "');"

    execount = conn.mysql_insertid(sql, dbname, cid)
    return execount


# 插入调用机器人记录（电话）
def insetCallrecordsphone(cid, text, flag, cmpid, channerlid, clevel, location, serviceid, operation, session_data,
                          session_sort, dbname):
    sql = """
     insert	into zy_rcustomerquestion(
 	cid,contet,questionFlag,cmpid,Tdata,channerlid,clevel,location,serviceid,operation,session_data,session_sort)
values('{}','{}','{}','{}',now(),'{}','{}','{}','{}','{}','{}','{}')
    """.format(
        cid, text, flag, cmpid, channerlid, clevel, location, serviceid, operation, session_data, session_sort
    )
    return conn.mysql_insertid(sql, dbname, cid)


# 存储特殊符号
def getsymbol(dbname, cid):
    sql = " select GROUP_CONCAT(rp.`separator` SEPARATOR '') as seq from zy_rseparator rp; "
    seq = conn.mysql_selrowid(sql, dbname, cid)
    return seq


# 判断是否存在接口名称
def jugeurlname(cmpid, urlname, dbname, cid):
    sql = " select rl.urlid from zy_rurl rl where rl.cmpid=" + str(cmpid) + "  and rl.urlname='" + str(
        urlname) + "' and rl.state=1; "
    urlid = conn.mysql_seldic(sql, dbname, cid)
    return urlid


# 判断特殊符号是否相等
def jugeequalseq(cmpid, urlname, ordersymbol, dbname, cid):
    sql = " select seq.urlid from  ( \
           select GROUP_CONCAT(rsp.`separator` ORDER BY RP.paramorder SEPARATOR '' ) as seq,rl.urlid from zy_rurl rl LEFT JOIN (zy_rurlparam rp,zy_rseparator rsp)  \
           on rp.urlid=rl.urlid and rsp.separatorid=rp.separatorid AND RP.state=1   \
            WHERE  rl.urlname='" + str(urlname) + "' and rl.cmpid=" + str(
        cmpid) + " and rl.state=1 GROUP BY RP.urlid ORDER BY RP.paramorder ) "
    if ordersymbol == "":
        sql = sql + " seq where seq.seq is null; "
    else:
        sql = sql + " seq  where seq.seq = '" + str(ordersymbol) + "'"
    urlid = conn.mysql_sel(sql, dbname, cid)
    return urlid


# 插入调用接口记录
def inscallurl(sessionid, urlid, url, dbname, cid):
    sql = " insert into zy_rcallurl(sessionid,urlid,url,Tdata)  \
          value (" + str(sessionid) + "," + str(urlid) + " ,'" + str(url) + "',now())   ;"
    insertcount = conn.mysql_insert(sql, dbname, cid)
    return insertcount


# 查询百度连接
def selbaiduurl(regurl, href, req, isend):
    # 查询url
    imgreurl = re.compile(regurl)
    urlurl = re.findall(regurl, req.text)
    if len(urlurl) > 0:
        hrefurl = re.compile(href)
        url = re.findall(hrefurl, urlurl[0])
        if len(url) > 0:
            baiduurl = url[0].replace('href="', '')
            return ('1', baiduurl)
        else:
            hrefurl = re.compile(href)
            url = re.findall(r'http:[^\t\n\r\f\v"]+\'', urlurl[0])
            if len(url) > 0:
                baiduurl = url[0].replace('http:"', '')
                return ('1', baiduurl)
            if isend == 1:
                return ('2', '')
            return ('2', urlurl)
    return ('', '')


def jugeurl(href, urltext):
    if href == "":
        return urltext
    return href


# 正则匹配json
# def jsondata(city):
# print(city)
##    url = "http://www.sojson.com/open/api/weather/json.shtml?city="+str(city)+""
##    req = rs.get(url)
##    data= req.json()
# if data['status']==200:
# return (city +'，'+str(data['date'][:4])+ '年' +data['date'][5:7]+ '月'+ data['data']['forecast'][0]['date']+'，日出时间：'+data['data']['forecast'][0]['sunrise']
# + '，日落时间：'+data['data']['forecast'][0]['sunset']+ '，最'+data['data']['forecast'][0]['high']+
##                '，最'+data['data']['forecast'][0]['low']+ '，'+data['data']['forecast'][0]['fx']+ '，'+data['data']['forecast'][0]['type']
##              + '，'+data['data']['forecast'][0]['notice']+'。'
##                + data['data']['forecast'][1]['date']+'，日出时间：'+data['data']['forecast'][1]['sunrise']
# + '，日落时间：'+data['data']['forecast'][1]['sunset']+ '，最'+data['data']['forecast'][1]['high']+
##                '，最'+data['data']['forecast'][1]['low']+ '，'+data['data']['forecast'][1]['fx']+ '，'+data['data']['forecast'][1]['type']
##              + '，'+data['data']['forecast'][1]['notice']+'。'
# )
# else:
# return ''

# 正则匹配json
def jsondata(city, num):
    try:
        # V4rSDhbK6A47KUzk8xbu6ihxqOETVzvy
        # 6tYzTvGZSOpYB5Oc2YGGOKt8
        url = "http://api.map.baidu.com/telematics/v3/weather?location=" + str(
            city) + "&output=json&ak=KaGKqtkTu27IMaIF2dRe5yK3LT6l9wXf"
        req = rs.get(url)
        data = req.json()

        if data['status'] == 'success':
            return data['results'][0]['currentCity'] + ',' + data['results'][0]['weather_data'][num]['date'] + ' 温度区间' + \
                data['results'][0]['weather_data'][num]['temperature'] \
                + ' ' + data['results'][0]['weather_data'][num]['weather'] + data['results'][0]['weather_data'][num][
                'wind'] + ',' + data['results'][0]['index'][num]['des']

        else:
            return ''
    except:
        return '查询天气接口出错！请联系管理员！'


def jsonweat(city, num):
    try:
        # V4rSDhbK6A47KUzk8xbu6ihxqOETVzvy
        # 6tYzTvGZSOpYB5Oc2YGGOKt8
        url = "https://www.sojson.com/open/api/weather/json.shtml?city=" + str(city) + ""

        req = rs.get(url)
        data = req.json()

        if str(data['status']) == '200':
            return data['city'] + data['data']['forecast'][num]['date'] + data['data']['forecast'][num]['high'] \
                + ' ' + data['data']['forecast'][num]['low'] + data['data']['forecast'][num]['notice']

        else:
            return ''
    except:
        return '输入有误'


# 遍历词查询天气接口
def selweatherurl(text):
    try:
        seg_list = jieba.cut(text, cut_all=False)
        ci = " ".join(seg_list)  # 精确模式
        num = 0
        if '明天' in text:
            num = 1
        elif '后天' in text:
            num = 2
        elif '大后天' in text:
            num = 3
        for city in ci.split(' '):
            if len(city) >= 2 and city not in ['天气', '怎么样', '如何']:
                weather = jsondata(city, num)
                if weather != "":
                    return weather

        return '不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?'
    except:
        return '不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?'


# 百度百科
def getbaidutext(baidutext):
    try:
        baiduurl = ""
        url = "http://www.baidu.com.cn/s?wd=" + baidutext + "&cl=3"
        req = rs.post(url, timeout=10)

        # 正则
        reg = r'<div class="c-span18 c-span-last">[ \n]*<p>[ \n]*[^\t\n\r\f\v]*'
        imlist = re.findall(reg, req.text)

        if len(imlist) > 0:
            # 查询百度链接
            urltext = r'<div class="c-span18 c-span-last">[ \n]*<p>[ \n]*[^\t\n\r\f\v]*[ \n]*[^\t\n\r\f\v]*[ \n]*[^\t\n\r\f\v]*[ \n]*[^\t\n\r\f\v]*'
            urlhref = r'href="[^\t\n\r\f\v"]+'
            getnewtex = selbaiduurl(urltext, urlhref, req, 0)

            if getnewtex[0] == '2':
                imlist = getnewtex[1]
                # 重新查找链接
                urltext = r'<div class="c-span18 c-span-last">[ \n]*<p>[ \n]*[^\t\n\r\f\v]*[ \n]*[^\t\n\r\f\v]*[ \n]*[^\t\n\r\f\v]*[ \n]*[^\t\n\r\f\v]*[ \n]*[^\t\n\r\f\v]*[ \n]*[^\t\n\r\f\v]*[ \n]*[^\t\n\r\f\v]*'
                urlhref = r'href="[^\t\n\r\f\v"]+'
                baiduurl = selbaiduurl(urltext, urlhref, req, 1)[1]

            else:
                baiduurl = getnewtex[1]

        else:
            reg = r'<div class="c-span18 c-span-last">*[ \n]*[^\t\n\r\f\v]*<div class="f13">'
            # imgre=re.compile(reg)
            imlist = re.findall(reg, req.text)
            # 查询百度链接
            urltext = r'<div class="c-span18 c-span-last">*[ \n]*[^\t\n\r\f\v]*<div class="f13">*[^\t\n\r\f\v]+?</a>'
            urlhref = r'href="[^\t\n\r\f\v"]+'

            getnewtex = selbaiduurl(urltext, urlhref, req, 0)
            if getnewtex[0] == '1':
                baiduurl = getnewtex[1]

        # baiduurl=
        # 如果有数据
        if len(imlist) > 0:
            re_br = re.compile('<br\s*?/?>')  # 处理换行
            re_h = re.compile('</?\w+[^>]*>')  # HTML标签
            blank_line = re.compile('\n+')
            imlist[0] = blank_line.sub('', imlist[0])
            imlist[0] = re_br.sub('', imlist[0])  # 将br转换为换行
            imlist[0] = re_h.sub('', imlist[0])  # 去掉HTML 标签
            imlist[0] = imlist[0].replace(' ', "")

            return (imlist[0], baiduurl)

        return ('不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?', baiduurl)
    except:
        return ('不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?', '')


# 拼接接口
def geturl(urlid, text, begin, sessionid, dbname, cid):
    try:
        sql = " select rl.urladdress from zy_rurl rl where rl.urlid=" + str(urlid) + " "
        url = conn.mysql_sel(sql, dbname, cid)
        if url != conn.err:
            sql = " SELECT up.urlparam,sp.`separator` from zy_rurlparam up,zy_rseparator sp \
                  where  up.urlid='" + str(urlid) + "' and sp.separatorid=up.separatorid and up.state=1; "
            urlparam = conn.mysql_sel(sql, dbname, cid)
            # 拼接接口
            if urlparam != conn.err:
                text = text[int(begin):]
                intbegi = 0
                url2 = ''
                for param in urlparam:
                    index = text.index(param[1])
                    if intbegi == 0:
                        url2 = url2 + "?" + param[0] + "=" + text[:int(index)]
                    else:
                        url2 = url2 + "&" + param[0] + "=" + text[:int(index)]
                    intbegi += 1
                    if len(text) != int(index) + 1:
                        text = text[int(index + 1):]
                    else:
                        pass
                urllink = url[0][0] + url2
                # 插入调用接口记录
                inscount = inscallurl(sessionid, urlid, urllink, dbname, cid)
                if inscount > 0:
                    return urllink
                else:
                    return conn.err
            else:
                return conn.err
        else:
            return conn.err
    except:
        return conn.err


# 判断是否调用接口
def jugecallurl(cmpid, text, sessionid, dbname, cid):
    try:
        if text.rfind(':') > -1:
            # 获取最后的：的位置
            indexlocation = len(text) - text[::-1].index(':')
            symbol = getsymbol(dbname, cid)
            urlname = text[:int(indexlocation)]
            # 获取特殊符号             #截取：后面的字符串
            subsymbol = search_same(list(text[int(indexlocation):]), list(symbol))
            # 判断是否符合接口模型
            url = jugeequalseq(cmpid, urlname, subsymbol, dbname, cid)
            # 判断是否调用接口
            if len(url) > 0:
                urlid = url[0][0]
                urllink = geturl(urlid, text, indexlocation, sessionid, dbname, cid)
                if urllink != conn.err:
                    try:
                        # 开始调用接口
                        req = rs.post(urllink, timeout=60)
                        return json.dumps(req.json(), sort_keys=True, indent=4, ensure_ascii=False)
                    # print(json.dumps("{'b':789,'c':456,'a':123}",sort_keys=True,indent=4))
                    ##                    call = rs.session()
                    ##                    r = call.get(urllink)
                    ##                    back = eval(r.text)
                    # return back
                    except:
                        return '执行接口出错！请检查接口配置是否正确！'
            else:
                return ''
        else:
            return ''
    except:
        return conn.err


def search_same(A, B):
    # 初始化
    AB = ''
    start = 0
    len_B = len(B)

    for x in A:
        for i in range(start, len_B):
            y = B[i]
            # 1.找到相同元素：追加到AB列表中
            if x == y:
                AB += x
    return AB


# 判断寒暄是否开启
def judgegreetingopen(cmpid, dbname, cid):
    sql = " select cr.smalltalk from zt_cmp_robot cr where cr.cmpid=" + str(cmpid) + " ;"
    ifopen = conn.mysql_selrowid(sql, dbname, cid)
    return ifopen


# 判断百度百科是否开启
def judgebaiduopen(cmpid, dbname, cid):
    sql = "select cr.biadu from zt_cmp_robot cr where cr.cmpid=" + str(cmpid) + " ;"
    ifopen = conn.mysql_selrowid(sql, dbname, cid)
    return ifopen


# 返回json
def backtype(code, cid, backtype, backanswer):
    backtuple = {'code': str(code), 'cid': cid, 'backtype': str(backtype), 'backanswer': backanswer}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s', backtuple)
    return backcon


# 返回listjson
def backtypeurl(code, cid, backtype, backanswer, url):
    backtuple = {'code': str(code), 'cid': cid, 'backtype': str(backtype), 'backanswer': backanswer, 'url': url}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s', backtuple)
    return backcon


# 返回json
def backtypequestionlist(code, cid, backtype, backanswer, info, questionlist):
    backtuple = {'code': str(code), 'cid': cid, 'backtype': str(backtype), 'backanswer': backanswer, 'info': info,
                 'questionlist': questionlist}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s', backtuple)
    return backcon


# 返回json
def backtypeadd(code, cid, backtype, backanswer, choiceback):
    backtuple = {'code': str(code), 'cid': cid, 'backtype': str(backtype), 'backanswer': backanswer,
                 'choiceback': str(choiceback)}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s', backtuple)
    return backcon


# 返回listjson
def backtypeurladd(code, cid, backtype, backanswer, url, choiceback):
    backtuple = {'code': str(code), 'cid': cid, 'backtype': str(backtype), 'backanswer': backanswer, 'url': url,
                 'choiceback': str(choiceback)}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s', backtuple)
    return backcon


# 返回json
def backtypequestionlistadd(code, cid, backtype, backanswer, info, questionlist, choiceback):
    backtuple = {'code': str(code), 'cid': cid, 'backtype': str(backtype), 'backanswer': backanswer, 'info': info,
                 'questionlist': questionlist, 'choiceback': str(choiceback)}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s', backtuple)
    return backcon


# 返回数据与分页数
def backpagedata(code, page, allpage, allcount, alldata):
    backtuple = {'code': str(code), 'page': str(page), 'allpage': str(allpage), 'allcount': str(allcount),
                 'alldata': alldata}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s', backtuple)
    return backcon


# 返回标准词详情
def backdata(code, data):
    backtuple = {'code': str(code), 'data': data}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s', backtuple)
    return backcon


# m表情包
# A问题库
# b附件和图片
# 根据编码获取数据

def foridgetanswer(datatype, dataid, dbname, cid):
    back = ''
    if datatype == 'm':
        sql = " select e.backexpression from zy_rexpression e where e.expressionid='" + str(dataid) + "' "
        back = conn.mysql_selrowid(sql, dbname, cid)
    if datatype == 'A':
        sql = " select ka.answertype,ka.answer,ka.remark from zt_know_answer ka where ka.answerid='" + str(
            dataid) + "'   "
        back = conn.mysql_sel(sql, dbname, cid)

    if datatype == 'b':
        sql = " select s.content,(case when s.usetype=1 then 1 when s.usetype=2 then 3 when " \
              " s.usetype=3 then 4 when s.usetype=4 then 5 else 0 end) from zt_know_source s where s.sourceid='" + str(
                  dataid) + "' and s.state=1  "
        back = conn.mysql_sel(sql, dbname, cid)
    return back


def selanswerdata(datatype, quesid, cid, session_data, session_sort, dbname):
    # 查询有多少个答案
    sqlanswercount = "select count(*) from zt_know_answer a where a.quesid='" + str(quesid) + "' "
    allcount = conn.mysql_selrowid(sqlanswercount, dbname, cid)
    web_logger.info('cid:%s quesid:%s answercount:%s', cid, quesid, allcount)
    if allcount == 0:
        sql = """
        SELECT
            ka.answertype,ka.answer,ka.remark,ka.qtype,ka.type,ka.content,q.interrupt,q.attrids,ka.voxfile,ka.itemid
        FROM
            zt_know_question q ,zt_know_answer ka
        WHERE
            ka.answerid=q.answerid
            AND q.quesid='{}'
        """.format(quesid)
        back = conn.mysql_sel(sql, dbname, cid)
        return back
    if str(allcount) == '1':
        sql = """
        SELECT
            ka.answertype,ka.answer,ka.remark,ka.qtype,ka.type,ka.content,q.interrupt,q.attrids,ka.voxfile,ka.itemid
        FROM
            zt_know_answer ka,zt_know_question q
        WHERE
            q.quesid=ka.quesid
            AND ka.quesid= '{}'
        """.format(quesid)

    else:
        # 查询客户标签符合条件的答案
        sql = """
            select
                ka.attrids,ka.answerid
            from
                zt_know_answer ka
            where
                ka.quesid='{}'
                and ka.attrids is not null
                and  ka.attrids!=''
        """.format(quesid)
        datalist = conn.mysql_sel(sql, dbname, cid)
        datalist_dict = dict(datalist)
        web_logger.info('cid:%s quesid:%s datalist_dict:%s', cid, quesid, datalist_dict)
        if len(datalist) != 0:
            web_logger.info('cid:%s quesid:%s datalist:%s', cid, quesid, datalist)
            for data in datalist:
                sql_value_attrid = "select l.attrid from zt_sale_data s ,zt_customer_attr_link l where s.saleid='" + str(
                    cid) + "' and l.tmcustid = s.temporarycustomerid"
                value_attrid_sel = conn.mysql_sel(sql_value_attrid, dbname, cid)
                sql_attrid = " SELECT count(*) from (select l.attrid from zt_sale_data s ,zt_customer_attr_link l where s.saleid='" + str(
                    cid) + "' and l.tmcustid = s.temporarycustomerid) a"
                count = conn.mysql_selrowid(sql_attrid, dbname, cid)
                web_logger.info('cid:%s quesid:%s value_attrid_sel:%s count:%s', cid, quesid, value_attrid_sel, count)

                if count != 0:
                    value_attrid_list = [str(j) for j in [i[0] for i in value_attrid_sel]]
                    for z in datalist_dict:
                        if z in value_attrid_list:
                            value_attrid = z

                    answerid = datalist_dict[value_attrid]
                    web_logger.info('cid:%s quesid:%s value_attrid_list:%s value_attrid:%s answerid:%s', cid, quesid,
                                    value_attrid_list, value_attrid, answerid)
                    # 查询对应的答案编码
                    sql_answer = "select ka.answertype,ka.answer,ka.remark,ka.qtype,ka.type,ka.content,q.interrupt,q.attrids,ka.voxfile,ka.itemid from zt_know_answer ka,zt_know_question q  where q.quesid=ka.quesid and ka.answerid='" + str(
                        answerid) + "'"
                    back = conn.mysql_sel(sql_answer, dbname, cid)
                    web_logger.info('datalist不为空 cid:%s quesid:%s back:%s', cid, quesid, back)
                    return back

        quesidcount = "select count(*) from zt_cmp_robot_respond r where r.questionid = '" + str(
            quesid) + "' and r.cid='" + str(cid) + "' "
        if session_data != "" and session_sort != "":
            quesidcount += " and r.session_data!='" + str(session_data) + "'"
        num = conn.mysql_selrowid(quesidcount, dbname, cid)
        if num == None or num == '':
            num = 0
        count = 0

        if str(allcount) != '0':
            # count = 0
            count = int(int(num) % int(allcount))
            if count != 0:
                count = count - 1
            else:
                count = allcount - 1
        sql = "select ka.answertype,ka.answer,ka.remark,ka.qtype,ka.type,ka.content,q.interrupt,q.attrids,ka.voxfile,ka.itemid from zt_know_answer ka,zt_know_question q  where q.quesid=ka.quesid and ka.quesid='" + str(
            quesid) + "' and (ka.attrids is  null or ka.attrids='') order by sort LIMIT " + str(count) + ",1   "
    back = conn.mysql_sel(sql, dbname, cid)
    web_logger.info('datalist为空 cid:%s quesid:%s back:%s', cid, quesid, back)
    return back


# 查询公司详情
def getcmpinfo(cmpid, num, dbname, cid):
    sql = " select (case when " + str(num) + " = 1 then c.CMPNAME  when " + str(num) + " = 2 then c.email \
            when " + str(num) + " = 3 then c.fax when " + str(num) + " = 4 then c.telephone \
            when " + str(num) + " = 5 then c.REGISTERADDR when " + str(num) + " = 6 then CMPMEMO  \
            when " + str(num) + " = 7 then r.nickname else '' END) from zt_company c,zt_cmp_robot r \
            where r.cmpid=c.COMPANYID   and c.COMPANYID= " + str(cmpid) + " ;"
    back = conn.mysql_selrowid(sql, dbname, cid)
    if back == None:
        back = "该公司还未设置！"
    return back


# 查询公司添加的新词
def selcmpnewword(cmpid, dbname, cid):
    sql = "select w.newword,w.wordrate,w.wordpro from zy_robotword w where w.cmpid='" + str(cmpid) + "'"
    newwordtxt = conn.mysql_sel(sql, dbname, cid)
    newlist = ()
    if newwordtxt != ():
        for row in newwordtxt:
            newlist += (row[0],)
    jieba.load_userdict(newlist)


# 查询寒暄回答
def selgreeting(greetingid, channelid, dbname, cid):
    sql = 'select g.greetingans from zy_robot_greeting g where g.greetingid=' + str(greetingid) + ''
    greetingans = conn.mysql_selrowid(sql, dbname, cid)
    return greetingans


# 查询寒暄语
def choiceanswer4(text, cmpid, channelid, dbname, cid):
    try:
        # 判断寒暄是否开启
        if judgegreetingopen(cmpid, dbname, cid) == 1:

            # 访问寒暄库
            anww = mongorobot.getgreeting(cmpid, text)

            if anww != '不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?':
                back = selgreeting(anww, channelid, dbname, cid)

                return (back, 1, 4)

    except:
        pass


# 查询表情回复
def choiceanswer6(text, cmpid, dbname, cid):
    if text[:2] == '/:' or text.find('/:') > 0:
        ans = mongorobot.getmood(text)
        ans = foridgetanswer(ans[:1], ans[1:], dbname, cid)
        return (ans, 1, 6)


# 查询图片回复
def choiceanswer8(text, cmpid, dbname, cid):
    if text[:7] == 'http://':
        ans = '系统暂时不提供此功能！'
        return (ans, 1, 8)


# 查询公司简介
def choiceanswer9(text, cmpid, dbname, cid):
    ans = mongorobot.selcompany(text)
    if ans[:1] == 'c':  # 公司详情
        ans = getcmpinfo(cmpid, ans[1:], dbname, cid)
        return (ans, 1, 9)


# 百度百科接口
def choiceanswer10(text, cmpid, dbname, cid):
    # 判断是否开启百度百科
    if judgebaiduopen(cmpid, dbname, cid) == 1:
        # 百度百科
        anww = getbaidutext(text)
        if anww[0] != '不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?':
            return (anww[0], jugeurl(anww[1], "http://www.baidu.com.cn/s?wd=" + text + "&cl=3"), 3, 10)


# 查询天气
def choiceanswer13(text, cmpid):
    anww = selweatherurl(text)
    if anww != '不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?':
        return (anww, 1, 13)


# 查询问题库
def choiceanswerA(text, cmpid, cid, serviceid, dbname):
    # 访问问题库
    ifhavetable = mongodbcon.seltable(str(dbname) + 'database' + str(cmpid))
    ans = mongorobot.getanw(cmpid, text, cid, serviceid, dbname)
    # print(ans,ifhavetable,'database' + str(cmpid))
    if ans != '不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?' and str(ifhavetable) != '0':
        # print('fff')
        if ans[:1] == 'A':
            queli = correlation(ans[1:], dbname, cid)
            # print('queli',queli)
            if len(queli) > 0:
                return (foridgetanswer('A', ans[1:], dbname, cid)[0][1], '根据您的问题，为您推荐以下关联问题，希望对您有帮助', queli, 7, 12)
            else:
                anstypedata = foridgetanswer('A', ans[1:], dbname, cid)
                # print('anstypedata',anstypedata)
                if anstypedata[0][0] == 2:
                    return (anstypedata[0][1], 9, 1, ans[1:])
                else:
                    return (anstypedata[0][1], 1, 1, ans[1:])
        elif ans[:1] == 'b':
            return (ans[1:], 4, 7)

    elif ans == '不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?' and str(ifhavetable) != '0':
        return choiceanswerB(text, cmpid, dbname, cid)


# 修改变量
def updataintentionvariant(variant, cid, dbname):
    gvalue = variant[2:-1]
    # 查询词典名称对应的grooveid

    grooveid = selwordgrooveid(gvalue, memcachcon.if_exist(str(dbname) + 'intentionrecord' + str(cid)), dbname, cid)
    data = selintentionkey(grooveid, cid, memcachcon.if_exist(str(dbname) + 'Globalkeymainid' + str(cid)), dbname)
    if data == None:
        data = ""
    return data


# 意图变量
def intentionvariant(HoodleMobileadress, cid, voiceortext, cmpid, dbname):
    reg = r'\$\{[^{}]*\}'  # ${tqcx}
    variantlist = re.findall(reg, HoodleMobileadress)

    if str(voiceortext) == '1':
        for variant in variantlist:
            if variant.count('#') == 2:
                type = variant.split('#')[1]

                if str(type) == '1':  # 信息变量
                    unvariant = variant.split('#')[-1][:-1]
                    data = str(variantdata(unvariant, cid, dbname))
                    HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
                elif str(type) == '2':  # 自定义变量
                    unvariant = variant.split('#')[0][1:]
                    data = str(odervariantdata(unvariant, cid, cmpid, dbname))
                    HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
            else:
                data = updataintentionvariant(variant, cid, dbname)
                HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)

    else:
        for variant in variantlist:
            if variant.count('#') == 2:
                type = variant.split('#')[1]

                if str(type) == '1':
                    unvariant = variant.split('#')[-1][:-1]

                    data = '&@' + str(variantdata(unvariant, cid, dbname)) + '&'
                    HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
                elif str(type) == '2':
                    unvariant = variant.split('#')[0][1:]
                    data = '&@' + str(odervariantdata(unvariant, cid, cmpid, dbname)) + '&'
                    HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
            else:
                data = '&@' + str(updataintentionvariant(variant, cid, dbname)) + '&'
                HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
    if HoodleMobileadress[0] == '&':
        HoodleMobileadress = HoodleMobileadress[1:]
    if HoodleMobileadress[-1] == '&':
        HoodleMobileadress = HoodleMobileadress[:-1]
    return HoodleMobileadress


# 文本变量多线程
def text_variant_thread(variant, cid, dbname, cmpid, HoodleMobileadress, userid):
    data = ''
    if variant.count('#') == 2:
        type = variant.split('#')[1]
        if str(type) == '1':  # 信息变量
            unvariant = variant.split('#')[-1][:-1]
            data = str(variantdata(unvariant, cid, dbname))
            # HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
        elif str(type) == '2':  # 自定义变量
            unvariant = variant.split('#')[0]
            data = str(odervariantdata(unvariant, cid, cmpid, dbname))
            # HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
        elif str(type) == '3':  # 信息变量海米
            select_value = variant.split('#')[-1][:-1]  # 去除最右边的括号
            data = str(variantdata1(userid, select_value, dbname, cid))  # 准备好替换数据
            # HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
        elif str(type) == '4':  # 一套话术公司变量
            select_value = variant.split('#')[-1][:-1]  # 去除最右边的括号
            #  print(select_value)
            itemid = select_value.split('#')[-1]  # 公司变量编码
            sharecmpid = memcachcon.if_exist(str(dbname) + 'sharecmpid' + str(cid))
            # print(sharecmpid)
            if sharecmpid:
                datacount = variant_cmp_info(sharecmpid, itemid, dbname, cid)
                if datacount[0][0] == 0:
                    data = variant_cmp_info_default(cmpid, itemid, dbname, cid)
                else:
                    data = datacount[0][1]
            else:
                data = variant_cmp_info_default(cmpid, itemid, dbname, cid)
            # HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
    return data


@time_statistic(1, 'cid')
def backvariant(HoodleMobileadress, cid, voiceortext, cmpid, userid, dbname):
    # print((HoodleMobileadress, cid, voiceortext, cmpid, userid,dbname))
    HoodleMobileadress = str(HoodleMobileadress)

    reg = r'\{[^{}]*\}'
    variantlist = re.findall(reg, HoodleMobileadress)
    web_logger.info('START cid:%s cmpid:%s  voiceortext:%s  HoodleMobileadress:%s variantlist:%s',
                    cid, cmpid, voiceortext, HoodleMobileadress, variantlist)
    if str(voiceortext) == '1':  # 文本变量
        text_variant_thread_data = locals()
        for index, variant in enumerate(variantlist):
            text_variant_thread_data[str(dbname) + str(index) + str(cid)] = ThreadWithReturnValue_lock(
                target=text_variant_thread,
                args=(variant, cid, dbname, cmpid, HoodleMobileadress, userid))
            text_variant_thread_data[str(dbname) + str(index) + str(cid)].start()
        for index, variant in enumerate(variantlist):
            variant_change_data = text_variant_thread_data[str(dbname) + str(index) + str(cid)].join()
            web_logger.info('cid:%s variant:%s variant_change_data:%s',
                            cid, variant, variant_change_data)
            HoodleMobileadress = str(HoodleMobileadress).replace(variant, variant_change_data)
    else:  # 语音变量
        HoodleMobileadress = thread_TTS_variant(variantlist, dbname, cid, cmpid, HoodleMobileadress, userid)
        if HoodleMobileadress[0] == '&':
            HoodleMobileadress = HoodleMobileadress[1:]
        if HoodleMobileadress[-1] == '&':
            HoodleMobileadress = HoodleMobileadress[:-1]
    web_logger.info('END cid:%s HoodleMobileadress:%s', cid, HoodleMobileadress)
    return str(HoodleMobileadress)


@time_statistic(0, 'cid')
def voice_variant(cid, cmpid, dbname, variant, HoodleMobileadress, userid, TTSIP, speed, voice, datatype, platformtype,
                  pitch_rate, informant):
    web_logger.info('START cid:%s cmpid:%s HoodleMobileadress:%s variant:%s', cid, cmpid, HoodleMobileadress, variant)
    data = '&'
    if variant.count('#') == 2:
        type = variant.split('#')[1]
        # print(type,'pppppppp')
        if str(type) == '1':
            unvariant = variant.split('#')[-1][:-1]
            variant_text_data = variantdata(unvariant, cid, dbname)
            # print('A')
            if variant_text_data != "":
                # 调用TTS接口获取录音地址
                address = get_TTS_voice_address(TTSIP, variant_text_data, cid, speed, voice, datatype, platformtype,
                                                pitch_rate, informant)
                if address != "":
                    data = '&' + str(address) + '&'
                web_logger.info('cid:%s cmpid:%s type:%s variant_text_data:%s tts_voice_address:%s data:%s', cid, cmpid,
                                type, variant_text_data, address, data)
            HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
        elif str(type) == '2':
            # print('B')
            unvariant = variant.split('#')[0]
            variant_text_data = odervariantdata(unvariant, cid, cmpid, dbname)
            if variant_text_data != "":
                address = get_TTS_voice_address(TTSIP, variant_text_data, cid, speed, voice, datatype, platformtype,
                                                pitch_rate,
                                                informant)
                if address != "":
                    data = '&' + str(address) + '&'
                web_logger.info('cid:%s cmpid:%s type:%s variant_text_data:%s tts_voice_address:%s data:%s', cid, cmpid,
                                type, variant_text_data, address, data)

            HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
        elif str(type) == '3':
            # print('C')
            select_value = variant.split('#')[-1][:-1]
            variant_text_data = variantdata1(userid, select_value, dbname, cid)
            if variant_text_data != "":
                address = get_TTS_voice_address(TTSIP, variant_text_data, cid, speed, voice, datatype, platformtype,
                                                pitch_rate,
                                                informant)
                if address != "":
                    data = '&' + str(address) + '&'
                web_logger.info('cid:%s cmpid:%s type:%s variant_text_data:%s tts_voice_address:%s data:%s', cid, cmpid,
                                type, variant_text_data, address, data)
            HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)
        elif str(type) == '4':
            # print('D')
            select_value = variant.split('#')[-1][:-1]
            itemid = select_value.split('#')[-1]  # 公司变量编码
            sharecmpid = memcachcon.if_exist(str(dbname) + 'sharecmpid' + str(cid))
            data = '&'
            web_logger.info('cid:%s cmpid:%s type:%s sharecmpid:%s', cid, cmpid, type, sharecmpid)
            if sharecmpid:
                datacount = variant_cmp_info(sharecmpid, itemid, dbname, cid)

                if datacount[0][0] == 0:
                    variant_text_data = variant_cmp_info_default(cmpid, itemid, dbname, cid)
                    if variant_text_data != "":
                        address = get_TTS_voice_address(TTSIP, variant_text_data, cid, speed, voice, datatype,
                                                        platformtype, pitch_rate, informant)
                        if address != "":
                            data = '&' + str(address) + '&'
                        web_logger.info(
                            'cid:%s cmpid:%s type:%s datacount:%s variant_text_data:%s tts_voice_address:%s data:%s',
                            cid, cmpid, type, datacount, variant_text_data, address, data)
                else:
                    address = get_TTS_voice_address(TTSIP, datacount[0][1], cid, speed, voice, datatype, platformtype,
                                                    pitch_rate, informant)
                    if address != "":
                        data = '&' + str(address) + '&'
                    web_logger.info('cid:%s cmpid:%s type:%s datacount:%s  tts_voice_address:%s data:%s', cid,
                                    cmpid, type, datacount, address, data)
            else:
                variant_text_data = variant_cmp_info_default(cmpid, itemid, dbname, cid)
                if variant_text_data != "":
                    address = get_TTS_voice_address(TTSIP, variant_text_data, cid, speed, voice, datatype, platformtype,
                                                    pitch_rate, informant)
                    if address != "":
                        data = '&' + str(address) + '&'
                    web_logger.info('cid:%s cmpid:%s type:%s variant_text_data:%s tts_voice_address:%s data:%s', cid,
                                    cmpid, type, variant_text_data, address, data)
            HoodleMobileadress = str(HoodleMobileadress).replace(variant, data)

    web_logger.info('END　cid:%s cmpid:%s HoodleMobileadress:%s variant:%s', cid, cmpid, HoodleMobileadress, variant)
    return HoodleMobileadress


@time_statistic(0, 'cid')
def voice_variant_change(cid, cmpid, dbname, variant, userid, TTSIP, speed, voice, datatype, platformtype, pitch_rate,
                         informant):
    web_logger.info('START cid:%s cmpid:%s variant:%s', cid, cmpid, variant)
    data = '&'
    if variant.count('#') == 2:
        type = variant.split('#')[1]
        # print(type,'pppppppp')
        if str(type) == '1':
            unvariant = variant.split('#')[-1][:-1]
            variant_text_data = variantdata(unvariant, cid, dbname)
            # print('A')
            if variant_text_data != "":
                # 调用TTS接口获取录音地址
                address = get_TTS_voice_address(TTSIP, variant_text_data, cid, speed, voice, datatype, platformtype,
                                                pitch_rate, informant)
                if address != "":
                    data = '&' + str(address) + '&'
                web_logger.info(
                    'cid:%s cmpid:%s type:%s unvariant:%s variant_text_data:%s tts_voice_address:%s data:%s',
                    cid, cmpid, type, unvariant, variant_text_data, address, data)
        elif str(type) == '2':
            unvariant = variant.split('#')[0]
            variant_text_data = odervariantdata(unvariant, cid, cmpid, dbname)
            if variant_text_data != "":
                address = get_TTS_voice_address(TTSIP, variant_text_data, cid, speed, voice, datatype, platformtype,
                                                pitch_rate,
                                                informant)
                if address != "":
                    data = '&' + str(address) + '&'
                web_logger.info(
                    'cid:%s cmpid:%s type:%s unvariant:%s variant_text_data:%s tts_voice_address:%s data:%s',
                    cid, cmpid, type, unvariant, variant_text_data, address, data)

        elif str(type) == '3':
            # print('C')
            select_value = variant.split('#')[-1][:-1]
            variant_text_data = variantdata1(userid, select_value, dbname, cid)
            if variant_text_data != "":
                address = get_TTS_voice_address(TTSIP, variant_text_data, cid, speed, voice, datatype, platformtype,
                                                pitch_rate,
                                                informant)
                if address != "":
                    data = '&' + str(address) + '&'
                else:
                    data = '&'
                web_logger.info(
                    'cid:%s cmpid:%s type:%s variant_text_data:%s tts_voice_address:%s data:%s',
                    cid, cmpid, type, variant_text_data, address, data)
        elif str(type) == '4':
            select_value = variant.split('#')[-1][:-1]
            itemid = select_value.split('#')[-1]  # 公司变量编码
            sharecmpid = memcachcon.if_exist(str(dbname) + 'sharecmpid' + str(cid))
            data = '&'
            web_logger.info('cid:%s cmpid:%s type:%s sharecmpid:%s', cid, cmpid, type, sharecmpid)
            if sharecmpid:
                datacount = variant_cmp_info(sharecmpid, itemid, dbname, cid)

                if datacount[0][0] == 0:
                    variant_text_data = variant_cmp_info_default(cmpid, itemid, dbname, cid)
                    if variant_text_data != "":
                        address = get_TTS_voice_address(TTSIP, variant_text_data, cid, speed, voice, datatype,
                                                        platformtype,
                                                        pitch_rate,
                                                        informant)
                        if address != "":
                            data = '&' + str(address) + '&'
                        web_logger.info(
                            'cid:%s cmpid:%s type:%s datacount:%s variant_text_data:%s tts_voice_address:%s data:%s',
                            cid, cmpid, type, datacount, variant_text_data, address, data)

                else:
                    address = get_TTS_voice_address(TTSIP, datacount[0][1], cid, speed, voice, datatype, platformtype,
                                                    pitch_rate,
                                                    informant)
                    if address != "":
                        data = '&' + str(address) + '&'
                    web_logger.info(
                        'cid:%s cmpid:%s type:%s  tts_voice_address:%s data:%s',
                        cid, cmpid, type, address, data)

            else:
                variant_text_data = variant_cmp_info_default(cmpid, itemid, dbname, cid)
                if variant_text_data != "":
                    address = get_TTS_voice_address(TTSIP, variant_text_data, cid, speed, voice, datatype, platformtype,
                                                    pitch_rate,
                                                    informant)
                    if address != "":
                        data = '&' + str(address) + '&'
                    web_logger.info('cid:%s cmpid:%s type:%s variant_text_data:%s tts_voice_address:%s data:%s', cid,
                                    cmpid, type, variant_text_data, address, data)

    web_logger.info('END cid:%s cmpid:%s variant:%s　data:%s', cid, cmpid, variant, data)
    return {'data': data, 'variant': variant}


class ThreadWithReturnValue_lock(threading.Thread):
    # mutex = threading.Lock()
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, daemon=None):
        Thread.__init__(self, group, target, name, args, kwargs, daemon=daemon)
        self._return = None

    def run(self):
        # global  mutex
        # if mutex.acquire():
        if self._target is not None:
            self._return = self._target(*self._args, **self._kwargs)
        # mutex.release()

    def join(self):
        Thread.join(self)
        return self._return


# 查询机器人的说话人
@time_statistic(2, 'cid')
def get_speech(onserviceid, dbname, cid):
    sql = "SELECT IFNULL(r.voice,'0.9') as  voice,IFNULL(r.speed,'0') as speed,IFNULL(r.informantid,'3') as informantid,IFNULL(i.remark,'Siyue') as remark,r.largestwordnum " \
          "from zt_cmp_robot r LEFT JOIN zt_dict_informant i on i.informantid=r.informantid  where r.onserviceid=" + str(
              onserviceid) + ""
    data = conn.mysql_seldic(sql, dbname, cid)
    return data


# 语音变量多线程
@time_statistic(2, 'cid')
def thread_TTS_variant(variantlist, dbname, cid, cmpid, HoodleMobileadress, userid):
    web_logger.info('START cid:%s cmpid:%s HoodleMobileadress:%s variantlist:%s', cid, cmpid, HoodleMobileadress,
                    variantlist)

    TTS_variant_thread_data = locals()
    voice = memcachcon.if_exist(str(dbname) + 'TTS_voice' + str(cid))
    speed = memcachcon.if_exist(str(dbname) + 'TTS_speed' + str(cid))  # 语速
    platformtype = memcachcon.if_exist(str(dbname) + 'TTS_informantid' + str(cid))  # TTS平台
    informant = memcachcon.if_exist(str(dbname) + 'TTS_remark' + str(cid))  # 说话人
    for index, data in enumerate(variantlist):
        TTS_variant_thread_data[str(dbname) + str(index)] = ThreadWithReturnValue_lock(target=voice_variant_change,
                                                                                       args=(
                                                                                           cid, cmpid, dbname, data,
                                                                                           userid,
                                                                                           conn.TTSIP, speed, voice, '',
                                                                                           platformtype, 0, informant))
        TTS_variant_thread_data[str(dbname) + str(index)].start()
    for index, data in enumerate(variantlist):
        variant_change_data = TTS_variant_thread_data[str(dbname) + str(index)].join()
        web_logger.info('cid:%s cmpid:%s  variant_change_data:%s', cid, cmpid, variant_change_data)
        HoodleMobileadress = str(HoodleMobileadress).replace(variant_change_data['variant'],
                                                             variant_change_data['data'])
        web_logger.info('cid:%s cmpid:%s  HoodleMobileadress:%s --1', cid, cmpid, HoodleMobileadress)
        HoodleMobileadress = HoodleMobileadress.replace('&&&&', '&').replace('&&&', '&').replace('&&', '&')
        web_logger.info('cid:%s cmpid:%s  HoodleMobileadress:%s --2', cid, cmpid, HoodleMobileadress)
    return HoodleMobileadress


# 查询转号码对应的客服号码
def sel_sphone(cid, itemid):
    sql = "SELECT c.content from zt_customer_tm_diy_item_content c,zt_sale_data d where c.itemid='" + str(
        itemid) + "'  and d.temporarycustomerid=c.tmcustomerid and d.saleid='" + str(cid) + "'"
    data = conn.mysql_selrowid(sql, conn.basedbname, cid)
    return data


@time_statistic(0, 'cid')
def backattachdata(cid, answerid, askid, cmpid, serviceid, sessionid, operation, session_data, session_sort, userid,
                   dbname):
    # 查询问题编码

    web_logger.info('START cid:%s serviceid:%s cmpid:%s operation:%s askid:%s answerid:%s', cid, serviceid, cmpid,
                    operation, askid, answerid)

    quesid = selquesid(answerid, dbname, cid)
    web_logger.info('cid:%s serviceid:%s cmpid:%s quesid:%s', cid, serviceid, cmpid, quesid)
    # 查询访问问题库相同内容多少次

    count = selaskcount(cid, quesid, session_data, dbname)
    web_logger.info('cid:%s serviceid:%s cmpid:%s count:%s', cid, serviceid, cmpid, count)

    if int(count) >= 3:
        to_much = selcommon(cmpid, serviceid, 1, 'to_much', dbname, cid)
        if len(to_much) != 0:
            back = globalvariable(to_much[0][0], to_much[0][1], to_much[0][2], to_much[0][3], cid, cmpid, serviceid,
                                  askid, 'to_much', '', to_much[0][4], to_much[0][5], to_much[0][6], session_data,
                                  session_sort, userid, dbname)

            if len(back) != 0 and back != None:
                return back

    HoodleMobileadress = ''
    HoodleMobileid = askid
    trunserviceid = ''
    iftrun = ''
    # 查询问题库是否有标签，有则倒入标签
    attrilist = selattrilist(quesid, dbname, cid)
    web_logger.info('cid:%s serviceid:%s cmpid:%s attrilist:%s', cid, serviceid, cmpid, attrilist)

    if attrilist != None and attrilist != '':
        tmcustid = seltmcustid(cid, dbname)
        attridlist = str(attrilist).split(',')
        for attrid in attridlist:
            insert_zt_customer_attr_link(tmcustid, cid, session_data, session_sort, attrid, dbname)

    anstypedata = selanswerdata('A', quesid, cid, session_data, session_sort, dbname)
    # print('转人工的anstypedata',anstypedata[0][4])
    # ka.answertype,ka.answer,ka.remark,ka.qtype,ka.type,ka.content,q.interrupt,q.attrids,ka.voxfile

    web_logger.info('cid:%s serviceid:%s cmpid:%s anstypedata:%s', cid, serviceid, cmpid, anstypedata)
    if len(anstypedata) != 0:
        # 存入标签
        anstype = str(anstypedata[0][4])
        # anstypedata[0][4] 1：问题跳转2：结束3：转人工 4转号码 5（机器人跳转）转子机器人了解详情6多轮会话
        if anstype == '1':
            # 回答问题库才跳转
            memcachcon.set_cach(str(dbname) + 'Jumpprocesses' + str(cid), anstypedata[0][5])

        elif anstype == '3':
            trunserviceid = anstypedata[0][5]
            iftrun = 1
            return Turntotheartificial(cmpid, serviceid, trunserviceid, cid, askid, '3', quesid, session_data,
                                       session_sort, userid, dbname)
        elif anstype == '4':
            phone = anstypedata[0][5]
            if anstypedata[0][9] != None:
                the_new_phone = sel_sphone(cid, anstypedata[0][9])
                if the_new_phone != "":
                    phone = the_new_phone

            iftrun = 1
            return Turnphone(cmpid, serviceid, phone, cid, askid, '3', quesid, session_data, session_sort, userid,
                             dbname)

        elif anstype == '5':
            memcachcon.set_cach(str(dbname) + 'childrobot' + str(cid), anstypedata[0][5])

            return skipscene(2, cmpid, anstypedata[0][5], cid, '', '', '3', quesid, session_data, session_sort, userid,
                             dbname)

        elif anstype == '6':

            return juntohoodel(anstypedata[0][5], cid, sessionid, operation, cmpid, '3', quesid, session_data,
                               session_sort, userid, dbname)
        else:
            memcachcon.set_cach(str(dbname) + 'answercach' + str(cid), 1)

        interrupt = "0"
        if str(anstypedata[0][6]) == '1':
            interrupt = ''

        # ka.answertype,ka.answer,ka.remark,ka.qtype,ka.type,ka.content,q.interrupt,q.attrids,ka.voxfile

        backchangedata = changebackdataforTTS(anstypedata[0][3], anstypedata[0][0], anstypedata[0][1],
                                              anstypedata[0][2],
                                              anstypedata[0][8], cmpid, userid, cid, dbname)
        web_logger.info('END cid:%s serviceid:%s cmpid:%s backchangedata:%s', cid, serviceid, cmpid, backchangedata)
        return (
            backchangedata['backtext'], backchangedata['backtype'], 1, answerid,
            'close' if anstypedata[0][4] == 2 else 'open', HoodleMobileid, trunserviceid,
            HoodleMobileadress, iftrun, backchangedata['backremark'], '', interrupt, '', '', '', '3', quesid,
            session_data,
            session_sort)  # 557788


# 查询是否还有问题
def ifhavaattachdata(cmpid, serviceid, cid, sessionid, operation, session_data, session_sort, userid, dbname):
    return endsentences(cmpid, serviceid, sessionid, cid, operation, '', '', session_data, session_sort, userid, dbname)


# 问题跳转答案
def Jumptheanswer(ans, cid, cmpid, askid, serviceid, sessionid, operation, session_data, session_sort, userid, dbname):
    if memcachcon.if_exist(str(dbname) + 'answercach' + str(cid)) != None:
        memcachcon.del_cach(str(dbname) + 'answercach' + str(cid))
    if memcachcon.if_exist(str(dbname) + 'notnextandbegin' + str(cid)) != None:
        memcachcon.del_cach(str(dbname) + 'notnextandbegin' + str(cid))

    return backattachdata(cid, ans[1:], askid, cmpid, serviceid, sessionid, operation, session_data, session_sort,
                          userid, dbname)


# 查询意图匹配
def matchingintention(serviceid, text, cmpid, dbname, cid):
    intentionall = selintention(serviceid, cmpid, dbname, cid)
    if intentionall != None and len(intentionall) > 0:
        ret_list = []
        maxret = 0
        expressionid = ''
        intentionkey = []
        intentionid = ''
        textlist = jieba.analyse.extract_tags(text, topK=50)

        for intentionmes in intentionall:
            intentionexpression = []
            if intentionmes[1] != "":
                allkey = selkeyvalue(intentionmes[2], dbname, cid)
                quexpresstion = intentionmes[1]
                if allkey != None:
                    for key in allkey:
                        quexpresstion = quexpresstion.replace(str(key[0]), '')

                intentionexpression = jieba.analyse.extract_tags(quexpresstion, topK=30)

            if len(textlist) > 0 and len(intentionexpression) > 0:
                # 交集
                intersection = list(
                    (set(intentionexpression).union(set(textlist))) ^ (set(intentionexpression) ^ set(textlist)))
                if len(intersection) > maxret:
                    maxret = len(intersection)
                    expressionid = intentionmes[0]
                    intentionkey = intentionexpression
                    intentionid = intentionmes[2]
        if expressionid != "":  # intentionid
            return (expressionid, textlist, intentionid)


# 提前关键字
def getintentionkeyvalue(text):
    textlist = jieba.analyse.extract_tags(text, topK=50)
    return textlist


# 识别词典是否存在
def recognitionwordin(wordstr, text):
    num = 0
    data = ''
    wordlist = wordstr.split("|")
    for word in wordlist:

        if word in text:
            lenword = len(word)
            if lenword > num:
                data = word
                num = lenword
    return data


# 匹配词槽并且记录
def pipe_dictionaries_word(expressionworddata, wordlist, cid, text, grooveid, keymainid, dbname):
    for expressionword in expressionworddata:

        if str(expressionword[1]) == '1':
            keyword = recognitionwordin(expressionword[0], text)
            if keyword != '':
                # 更新词槽
                insertintentionkey(cid, grooveid, keyword, keymainid, dbname)
                return ('1')
        if str(expressionword[1]) == '2':
            # 匹配正则

            redata = re.findall(expressionword[0], text)

            if len(redata) != 0:
                # 更新词槽
                insertintentionkey(cid, grooveid, redata[0], keymainid, dbname)
                return ('1')
    return ''


# 意图返回值
def backfinalyintentiondata(expressionid, askid, cid, sessionid, operation, backintentiondata, cmpid, session_data,
                            session_sort, dbname):
    # 获取参数 backintentiondata =m.endwords,m.type,m.remark,m.qtype,m.url,m.stype

    key = getintentionurlkey(memcachcon.if_exist(str(dbname) + 'Globalkeymainid' + str(cid)), cid, dbname)
    # 调用接口返回json
    urljson = invokingurljson(str(backintentiondata[0][4]) + '?' + str(key), cid)

    if 'err!!' in urljson:
        tupledata = ('调用第三方接口出错', 1, 1, '0', 'open', askid, '', '', '', '', '', '0', '', '', '', '', '', session_data,
                     session_sort)  # 557788
        return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)
    else:
        # 遍历返回的json数据
        for key in urljson:
            # 存储数据

            selstoragejsonitemintnetion(memcachcon.if_exist(str(dbname) + 'intentionrecord' + str(cid)), key,
                                        urljson[key], cid,
                                        cmpid, dbname)
        return feedbackdatatuple(backintentiondata, askid, cid, 1, cmpid, session_data, session_sort, dbname)


# 查询客户号码
def sel_phone_data(cid):
    sql = "select s.mobilephone from zt_sale_data s where s.saleid='" + str(cid) + "'"
    mobilephone = conn.mysql_selrowid(sql, conn.basedbname, cid)
    return mobilephone


# 意图返回值定制
def backfinalyintentiondata_ding(expressionid, askid, cid, sessionid, operation, backintentiondata, cmpid, session_data,
                                 session_sort, dbname):
    try:
        adress = sel_key_data(cid, dbname)
        phone = sel_phone_data(cid)
        # key = getintentionurlkey(memcachcon.if_exist(str(dbname)+'Globalkeymainid' + str(cid)), cid,dbname)
        # 获取电话号码
        # 调用接口返回json
        invokingurljson_post(cid, adress, phone)
        return feedbackdatatuple(backintentiondata, askid, cid, 1, cmpid, session_data, session_sort, dbname)
    except Exception as e:
        web_logger.warning('cid:%s  error:%s %s', cid, type(e), e)
        weixin_push("backfinalyintentiondata_ding", str(e), str(cid))


# 定义返回格式
def feedbackdatatuple(feeddata, askid, cid, type, cmpid, session_data, session_sort, dbname):
    # feeddata1：回答的内容2：类型(1:文本2录音)3：备注4：是否变量（1常量2：变量）
    # m.endwords,m.type,m.remark,m.qtype,m.url,m.stype,m.isend
    # back(1:backanswer2:backtype3:choiceback4:answerid5:conversation6:HoodleMobileid7:serviceid8:attach9:instructid10:memo11:attitude12:helloorbye13:collectid14:phone15:)  11和15是没有值的

    backtext = feeddata[0][0]
    backtype = 1
    backtextremak = ''

    if str(feeddata[0][3]) == '2':  # 变量
        if str(feeddata[0][1]) == '2':  # 类型录音
            backtype = 11
            backtext = intentionvariant(backtext, cid, 2, cmpid, dbname)
            backtextremak = intentionvariant(feeddata[0][2], cid, 1, cmpid, dbname)
        else:
            backtext = intentionvariant(backtext, cid, 1, cmpid, dbname)
    else:
        if str(feeddata[0][1]) == '2':  # 类型录音
            backtype = 9
            backtextremak = intentionvariant(feeddata[0][2], cid, 1, cmpid, dbname)
    if str(type) == "1":
        if memcachcon.if_exist(str(dbname) + 'intentionrecord' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'intentionrecord' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'nowexpression' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'nowexpression' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'Globalgrooveid' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'Globalgrooveid' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'Globalfeedbackcount' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'Globalfeedbackcount' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'Globalkeymainid' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'Globalkeymainid' + str(cid))
        if memcachcon.if_exist(str(dbname) + 'Globalnotinsertkey' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'Globalnotinsertkey' + str(cid))
    ifopen = 'open'
    if str(feeddata[0][6]) == '1':
        ifopen = 'close'

    dictionariesid = memcachcon.if_exist(str(dbname) + 'dictionariesid' + str(cid))
    the_type = ''
    the_num = ''
    if dictionariesid != None:
        the_type = 6
        the_num = dictionariesid
        memcachcon.del_cach(str(dbname) + 'dictionariesid' + str(cid))
    else:
        the_type = 5
        the_num = memcachcon.if_exist(str(dbname) + 'intentionrecord' + str(cid))
    return (
        backtext, backtype, 1, '', ifopen, askid, '', '', '', backtextremak, '', '', '', '', '', the_type, the_num,
        session_data,
        session_sort)  # 557788


# 查看未填词槽，如果全部填写就回复内容
def choicebackintention(expressionid, askid, cid, sessionid, operation, text, textlist, keymainid, cmpid, session_data,
                        session_sort, dbname):
    # 查看意图的词槽，查询词槽
    # groovedata  1:dictionariesid,2:grooveid

    groovealldata = expression_dictionaries(expressionid, '', keymainid, dbname, cid)

    if groovealldata != None and len(groovealldata) > 0:

        for groovedata in groovealldata:

            # 词槽列表1：列出案例 2：类型（1：词典2：正则）3所属词典编码，
            expressionworddata = selintentionkeyword(groovedata[0], dbname, cid)

            if expressionworddata != None and len(expressionworddata) != 0:
                # 查询匹配(expressionworddata,wordlist,cid,text,grooveid)
                pipe_dictionaries_word(expressionworddata, textlist, cid, text, groovedata[1], keymainid, dbname)

    # 查询是否是必填项
    return selifhaverequire(cid, expressionid, askid, sessionid, operation, keymainid, cmpid, session_data,
                            session_sort, dbname)


# 重新查询词槽，如果全部填写就回复内容
def choicebackintentionagant(expressionid, askid, cid, sessionid, operation, text, textlist, keymainid, cmpid,
                             session_data, session_sort, dbname):
    # 查看意图的词槽，查询词槽
    # groovedata  1:dictionariesid,2:grooveid
    groovealldata = expression_dictionariesagant(expressionid, '', keymainid, dbname, cid)

    if groovealldata != None and len(groovealldata) > 0:

        for groovedata in groovealldata:

            # 词槽列表1：列出案例 2：类型（1：词典2：正则）3所属词典编码，
            expressionworddata = selintentionkeyword(groovedata[0], dbname, cid)

            if expressionworddata != None and len(expressionworddata) != 0:
                # 查询匹配(expressionworddata,wordlist,cid,text,grooveid)
                pipe_dictionaries_word(expressionworddata, textlist, cid, text, groovedata[1], keymainid, dbname)

    # 查询是否是必填项
    return selifhaverequire(cid, expressionid, askid, sessionid, operation, keymainid, cmpid, session_data,
                            session_sort, dbname)


# 查询是否还有必填项，否则返回结果
@time_statistic(0, 'cid')
def selifhaverequire(cid, expressionid, askid, sessionid, operation, keymainid, cmpid, session_data, session_sort,
                     dbname):
    # 查询是否是必填项
    # f.返回的内容,f.返回的类型（1.文本2.录音）,f备注,f.是否变量（1常量2变量）,g.词槽编码

    grooveid = selgroove(cid, keymainid, dbname)
    if memcachcon.if_exist(str(dbname) + 'Globalfeedbackcount' + str(cid)) == None:
        memcachcon.set_cach(str(dbname) + 'Globalfeedbackcount' + str(cid), 1)
    else:
        Globalgrooveid_data = memcachcon.if_exist(str(dbname) + 'Globalgrooveid' + str(cid))
        if Globalgrooveid_data == None:
            memcachcon.set_cach(str(dbname) + 'Globalfeedbackcount' + str(cid), 1)
        else:
            if grooveid != None and str(grooveid) == str(Globalgrooveid_data):
                memcachcon.add_num(str(dbname) + 'Globalfeedbackcount' + str(cid))
            else:
                memcachcon.set_cach(str(dbname) + 'Globalfeedbackcount' + str(cid), 1)

    Globalfeedbackcount_data = memcachcon.if_exist(str(dbname) + 'Globalfeedbackcount' + str(cid))

    judgeback = ()
    if grooveid != None and grooveid != "":
        judgeback = getnotinputintention(cid, grooveid, keymainid, Globalfeedbackcount_data, dbname)

    if judgeback != None and len(judgeback) > 0:
        # for judgeback in judgeallback:
        memcachcon.set_cach(str(dbname) + 'Globalgrooveid' + str(cid), judgeback[0][4])
        # Globalgrooveid[str(cid)] = judgeback[0][4]
        # Globalgrooveid[str(cid)] = Globalgrooveid[cid]
        # Globalfeedbackcount[str(cid)] = 1
        # 查询询问的语句
        # feeddata = feedbackdata(judgeback[1])
        # 有返回的数据1：回答的内容2：类型(1:文本2变量)3：备注4：是否变量（1常量2：变量）
        # if feeddata!=None and len(feeddata)!=0:
        return feedbackdatatuple(judgeback, askid, cid, '', cmpid, session_data, session_sort, dbname)

    # 查询最后表达式执行的结果
    # m.endwords(返回内容),m.type（返回类型1文本 2语音）,m.remark(备注),m.qtype(1常量2变量),m.url,m.stype(1：直接回答2：调用接口回答2)
    # if len(intentionexpressionrecord[str(cid)])==1:
    #     del intentionexpressionrecord[str(cid)]
    # else:
    #     intentionexpressionrecord[str(cid)].remove(nowexpression[str(cid)])

    # 更新词槽状态
    updataKeymain(keymainid, dbname, cid)
    # m.endwords,m.type,m.remark,m.qtype,m.url,m.stype,m.isend
    backintentiondata = finallyintention(expressionid, dbname, cid)

    if str(backintentiondata[0][5]) == '1':  # 直接回答
        if int(memcachcon.if_exist(str(dbname) + 'intentionrecord' + str(cid))) == 24:  # 特定接口
            return backfinalyintentiondata_ding(expressionid, askid, cid, sessionid, operation, backintentiondata,
                                                cmpid,
                                                session_data, session_sort, dbname)
        return feedbackdatatuple(backintentiondata, askid, cid, '1', cmpid, session_data, session_sort, dbname)
    elif str(backintentiondata[0][5]) == '2':  # 调用接口

        return backfinalyintentiondata(expressionid, askid, cid, sessionid, operation, backintentiondata, cmpid,
                                       session_data, session_sort, dbname)


# 没有匹配的时候再获取意图
@time_statistic(2, 'cid')
def insertintnetionback(text, cmpid, cid, serviceid, sessionid, operation, askid, industryid, wordslotid, session_data,
                        session_sort, dbname):
    Globalgrooveid_data = memcachcon.if_exist(str(dbname) + 'Globalgrooveid' + str(cid))
    Globalkeymainid_data = memcachcon.if_exist(str(dbname) + 'Globalkeymainid' + str(cid))
    # if str(cid) in Globalgrooveid.keys():
    #     groovealldata = selgrooveidci(Globalgrooveid[str(cid)],Globalkeymainid[str(cid)])
    if Globalgrooveid_data != None:
        groovealldata = selgrooveidci(Globalgrooveid_data, Globalkeymainid_data, dbname, cid)
        if groovealldata != None and len(groovealldata) > 0:
            have = ''
            teslist = getintentionkeyvalue(text)
            for groovedata in groovealldata:
                # 词槽列表1：列出案例 2：类型（1：词典2：正则）3所属词典编码，

                expressionworddata = selintentionkeyword(groovedata[2], dbname, cid)
                if expressionworddata != None and len(expressionworddata) != 0:
                    # 查询匹配

                    # have = pipe_dictionaries_word(expressionworddata,teslist,cid,text,groovedata[3],Globalkeymainid[str(cid)])
                    have = pipe_dictionaries_word(expressionworddata, teslist, cid, text, groovedata[3],
                                                  Globalkeymainid_data, dbname)
                    if have != "":
                        # 记录匹配的词曹
                        memcachcon.set_cach(str(dbname) + 'dictionariesid' + str(cid), groovedata[2])
            if have == "":
                # Globalnotinsertkey[str(cid)] = 0
                memcachcon.set_cach(str(dbname) + 'Globalnotinsertkey' + str(cid), 0)

                # 循环提问
            else:
                # back =selifhaverequire(cid,nowexpression[str(cid)],askid,sessionid,operation,Globalkeymainid[str(cid)],cmpid)
                nowexpression_data = memcachcon.if_exist(str(dbname) + 'nowexpression' + str(cid))

                back = selifhaverequire(cid, nowexpression_data, askid, sessionid, operation, Globalkeymainid_data,
                                        cmpid, session_data, session_sort, dbname)
                if back != None:
                    return back
            # if str(cid) in Globalnotinsertkey.keys():
            #     if str(Globalnotinsertkey[str(cid)])=='0':
            #         del Globalnotinsertkey[str(cid)]
            #         Globalfeedbackcount[str(cid)] = Globalfeedbackcount[str(cid)] + 1
            #         judgeback = selbackfeeckcycle(Globalgrooveid[str(cid)],Globalfeedbackcount[str(cid)])
            #         if judgeback!=None and len(judgeback)>0:
            #             #有返回的数据1：回答的内容2：类型(1:文本2变量)3：备注4：是否变量（1常量2：变量）
            #             return feedbackdatatuple(judgeback,askid,cid)


# 意图
@time_statistic(2, 'cid')
def jugeintention(text, cmpid, cid, serviceid, sessionid, operation, askid, industryid, wordslotid, session_data,
                  session_sort, dbname):
    # 存在意图
    back = insertintnetionback(text, cmpid, cid, serviceid, sessionid, operation, askid, industryid, wordslotid,
                               session_data, session_sort, dbname)
    if back != None:
        return back
    # 查询意图
    expressiondata = matchingintention(serviceid, text, cmpid, dbname, cid)
    # expressiondata 1:expressionid 2:客户说的关键字3intentionid
    if expressiondata != None and len(expressiondata) != 0:

        # nowexpression[str(cid)]=expressiondata[0]  #表达式
        # if  str(cid)  in intentionrecord.keys():
        #     if str(intentionrecord[str(cid)])==str(expressiondata[2]):
        memcachcon.set_cach(str(dbname) + 'nowexpression' + str(cid), expressiondata[0])  # 表达式
        intentionrecord_data = memcachcon.if_exist(str(dbname) + 'intentionrecord' + str(cid))
        if intentionrecord_data != None:
            if str(intentionrecord_data) == str(expressiondata[2]):
                return choicebackintentionagant(expressiondata[0], askid, cid, sessionid, operation, text,
                                                expressiondata[1],
                                                memcachcon.if_exist(str(dbname) + 'Globalkeymainid' + str(cid)),
                                                cmpid, session_data, session_sort, dbname)

        web_logger.info('查询意图 cid:%s expressiondata:%s', cid, expressiondata)
        memcachcon.set_cach(str(dbname) + 'intentionrecord' + str(cid), expressiondata[2])  # #意图编码
        keymainid = install_key_main(cid, expressiondata[0], dbname)
        memcachcon.set_cach(str(dbname) + 'Globalkeymainid' + str(cid), keymainid)
        insalldata(cid, expressiondata[0], expressiondata[2], keymainid, dbname)

        return choicebackintention(expressiondata[0], askid, cid, sessionid, operation, text, expressiondata[1],
                                   keymainid, cmpid, session_data, session_sort, dbname)


# 存在意图没有匹配到问题库的时候
@time_statistic(0, 'cid')
def selnotquestionaskintention(cid, askid, sessionid, operation, cmpid, session_data, session_sort, dbname):
    nowexpression_data = memcachcon.if_exist(str(dbname) + 'nowexpression' + str(cid))
    web_logger.info('cid:%s nowexpression_data:%s', cid, nowexpression_data)
    if nowexpression_data != None:
        Globalnotinsertkey_data = memcachcon.if_exist(str(dbname) + 'Globalnotinsertkey' + str(cid))
        if Globalnotinsertkey_data != None:
            if Globalnotinsertkey_data == '0':
                memcachcon.del_cach(str(dbname) + 'Globalnotinsertkey' + str(cid))
                Globalfeedbackcount_data = memcachcon.if_exist(str(dbname) + 'Globalfeedbackcount' + str(cid))
                if Globalfeedbackcount_data != None:
                    memcachcon.add_num(str(dbname) + 'Globalfeedbackcount' + str(cid))
                else:
                    memcachcon.set_cach(str(dbname) + 'Globalfeedbackcount' + str(cid), 1)
                judgeback = selbackfeeckcycle(memcachcon.if_exist(str(dbname) + 'Globalgrooveid' + str(cid)),
                                              memcachcon.if_exist(str(dbname) + 'Globalfeedbackcount' + str(cid)),
                                              dbname, cid)
                web_logger.info('cid:%s judgeback:%s', cid, judgeback)
                if judgeback != None and len(judgeback) > 0:
                    # 有返回的数据1：回答的内容2：类型(1:文本2变量)3：备注4：是否变量（1常量2：变量）
                    return feedbackdatatuple(judgeback, askid, cid, '', cmpid, session_data, session_sort, dbname)
        back = selifhaverequire(cid, memcachcon.if_exist(str(dbname) + 'nowexpression' + str(cid)), askid, sessionid,
                                operation,
                                memcachcon.if_exist(str(dbname) + 'Globalkeymainid' + str(cid)), cmpid, session_data,
                                session_sort, dbname)
        if back != None:
            return back


# 问卷调查回答类型
@time_statistic(0, 'cid')
def question_back_type(cid, sessionid, operation, askid, wordslotid, session_data, session_sort, dbname):
    ans = ''
    try:
        # htypeid = memcachcon.if_exist(str(dbname) + 'sharetype' + str(cid))
        # 问卷匹配流程
        questionnairetype = memcachcon.if_exist(str(conn.basedbname) + 'questionnairetype' + str(askid) + str(cid))
        matchidlist = memcachcon.if_exist(str(conn.basedbname) + 'matchidlist' + str(askid) + str(cid))
        # 是问卷查看是否得出选出答案并且查看答案对应的下一个问题
        # questionnairetype问卷类型1：多选（且的关系）2：多选（或的关系）3：单选（或的关系）4.无标准答案

        if questionnairetype != None and matchidlist != None:
            web_logger.info('cid:%s matchidlist:%s questionnairetype:%s', cid, questionnairetype, matchidlist)
            have_matchidlist = memcachcon.if_exist(
                str(conn.basedbname) + 'have_matchidlist_askid' + str(askid) + str(cid))
            attitude_match = sel_questionnaire(askid, dbname, cid)
            if len(attitude_match) != 0:

                if have_matchidlist != None:
                    type_2_num = 0
                    type_1_num = 0
                    p_matchid = [int(i) for i in have_matchidlist]
                    p_matchid = list(set(p_matchid))
                    p_matchid = list(sorted(p_matchid, reverse=True))
                    for attitude in attitude_match:
                        attitude_list = attitude['matchid'].split(',')
                        attitude_list = [int(i) for i in attitude_list]
                        attitude_list = list(set(attitude_list))
                        h_matchid = list(sorted(attitude_list, reverse=True))
                        web_logger.info('cid:%s p_matchid:%s h_matchid:%s', cid, p_matchid, h_matchid)

                        # 问卷类型1：多选（且的关系）2：多选（或的关系）3：单选（或的关系）4.无标准答案
                        if str(questionnairetype) == '1':
                            p_matchid_num = len(h_matchid)
                            if h_matchid == p_matchid:
                                ans = 'attitude' + str(attitude["attitude"])
                            elif set(p_matchid) > set(h_matchid):
                                if ans == "":
                                    ans = 'attitude' + str(attitude["attitude"])
                                    type_1_num = p_matchid_num
                                elif p_matchid_num > type_1_num:
                                    ans = 'attitude' + str(attitude["attitude"])
                                    type_1_num = p_matchid_num

                        elif str(questionnairetype) == '2':
                            equality_num = len(list(set(h_matchid).intersection(set(p_matchid))))  # 交集
                            if equality_num > type_2_num:
                                ans = 'attitude' + str(attitude["attitude"])
                                type_2_num = equality_num
                        elif str(questionnairetype) == '3':
                            for h_matchid_data in h_matchid:
                                if h_matchid_data in p_matchid:
                                    if ans == '':
                                        ans = 'attitude' + str(attitude["attitude"])
                        elif str(questionnairetype) == '4':
                            for h_matchid_data in h_matchid:
                                if h_matchid_data in p_matchid:
                                    if ans == '':
                                        ans = 'attitude' + str(attitude["attitude"])
                    if len(attitude_match) != 0 and ans == "":
                        ignorecount = memcachcon.if_exist(str(conn.basedbname) + 'ignorecount' + str(askid) + str(cid))
                        if ignorecount == None:
                            ignorecount = 1
                            memcachcon.set_cach(str(conn.basedbname) + 'ignorecount' + str(askid) + str(cid), 1)
                        else:
                            ignorecount = int(ignorecount) + 1
                            memcachcon.set_cach(str(conn.basedbname) + 'ignorecount' + str(askid) + str(cid),
                                                ignorecount)
                        if int(ignorecount) < 10:
                            web_logger.info('问卷收集 cid:%s ans:%s ignorecount:%s', cid, ans, ignorecount)
                            tupledata = (
                                '问卷收集中', 1, 3, '0', 'open', askid, '', '', '7', '1', '', '', wordslotid, '', '', '7',
                                str(askid),
                                session_data, session_sort)  # 557788
                            return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)
                elif str(questionnairetype) == '3' or str(questionnairetype) == '2' or str(
                        questionnairetype) == '1' or str(questionnairetype) == '4':
                    ignorecount = memcachcon.if_exist(str(conn.basedbname) + 'ignorecount' + str(askid) + str(cid))
                    web_logger.info('问卷收集中 cid:%s ans:%s ignorecount:%s', cid, ans, ignorecount)
                    if ignorecount == None:
                        ignorecount = 1
                        memcachcon.set_cach(str(conn.basedbname) + 'ignorecount' + str(askid) + str(cid), 1)
                    else:
                        ignorecount = int(ignorecount) + 1
                        memcachcon.set_cach(str(conn.basedbname) + 'ignorecount' + str(askid) + str(cid), ignorecount)
                    if int(ignorecount) < 10:
                        tupledata = (
                            '问卷收集中', 1, 3, '0', 'open', askid, '', '', '7', '1', '', '', wordslotid, '', '', '7',
                            str(askid),
                            session_data, session_sort)  # 557788
                        return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)
        return ans
    except Exception as e:
        web_logger.warning('cid:%s  error:%s %s', cid, type(e), e)
        return ans


# 查询问题库
@time_statistic(2, 'cid')
def choiceanswerphoneA(text, cmpid, cid, serviceid, sessionid, operation, askid, industryid, wordslotid, session_data,
                       session_sort, userid, dbname, originalcmpid, get_digits=None):
    # 访问问题库
    web_logger.info('STATR cid:%s text:%s operation:%s serviceid:%s cmpid:%s askid:%s industryid:%s wordslotid:%s get_digits:%s',
                    cid, text, operation, serviceid, cmpid, askid,  industryid, wordslotid,  get_digits)
    question_back = question_back_type(cid, sessionid, operation, askid, wordslotid, session_data, session_sort, dbname)
    # 意图
    intentiondata = jugeintention(text, cmpid, cid, serviceid, sessionid, operation, askid,
                                  industryid, wordslotid, session_data, session_sort, dbname)
    if intentiondata != None:
        return intentiondata
    ans = mongorobot.getanwservice(cmpid, text, cid, serviceid, askid, operation, industryid, session_data,
                                   session_sort, dbname)
    web_logger.info('cid:%s serviceid:%s ans:%s intentiondata:%s question_back:%s',
                    cid, serviceid, ans, intentiondata, question_back)

    if text in ["没错"]:
        ans = "attitude1"

    writetxtbig('bigtxt', json.dumps({str(cid): str(ans)}))
    beforeoperation = memcachcon.if_exist(str(dbname) + 'operation' + str(cid))

    web_logger.info('cid:%s serviceid:%s beforeoperation:%s', cid, serviceid, beforeoperation)

    if beforeoperation != None and ans != 'attitude2' and ans != "attitude3":
        tupledata = (
            '开场白只可打断拒绝和否定', 1, 3, '0', 'open', askid, '', '', '4', '1', '', '', wordslotid, '', '', '', '',
            session_data,
            session_sort)  # 557788
        return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)
    elif beforeoperation != None and (ans == 'attitude2' or ans == 'attitude3'):
        memcachcon.del_cach(str(dbname) + 'operation' + str(cid))
    if ans != 'attitude6' and ans != "attitude7" and ans != "attitude11":
        web_logger.info('cid:%s serviceid:%s ans:%s', cid, serviceid, ans)
        if question_back != "" and question_back[0] == '{':
            return question_back
        elif question_back != "":
            ans = question_back
    if memcachcon.if_exist(str(dbname) + 'textnull' + str(cid)) != None:
        memcachcon.del_cach(str(dbname) + 'textnull' + str(cid))
    if ans != '不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?':
        web_logger.info('cid:%s ans:%s', cid, ans)
        if ans[:1] == 'A':
            if memcachcon.if_exist(str(dbname) + 'Jumpprocesses' + str(cid)) != None:
                memcachcon.del_cach(str(dbname) + 'Jumpprocesses' + str(cid))
            back = Jumptheanswer(ans, cid, cmpid, askid, serviceid, sessionid, operation, session_data, session_sort,
                                 userid, dbname)
            web_logger.info('流程跳转--ans--A开头 cid:%s ans:%s back:%s', cid, ans, back)
            if back != None and len(back) != 0:
                return back

        elif ans[:8] == 'attitude':
            web_logger.info('态度跳转--ans--attitude开头 cid:%s ans:%s', cid, ans)
            largestwordnum = memcachcon.if_exist(str(dbname) + 'largestword' + str(cid))

            if largestwordnum != None and len(text) >= int(largestwordnum) and ans == 'attitude5':
                largestwordcount = memcachcon.if_exist(str(dbname) + 'largestwordcount' + str(cid))
                if largestwordcount == None:
                    largestwordcount = 1
                    memcachcon.set_cach(str(dbname) + 'largestwordcount' + str(cid), 1)
                else:
                    largestwordcount = int(largestwordcount) + 1
                    memcachcon.set_cach(str(dbname) + 'largestwordcount' + str(cid), largestwordcount)
                largestword = selcommon(cmpid, serviceid, largestwordcount, 'largestword', dbname, cid)
                if len(largestword) != 0:
                    back = globalvariable(largestword[0][0], largestword[0][1], largestword[0][2], largestword[0][3],
                                          cid, cmpid, serviceid, askid,
                                          'largestword',
                                          '', largestword[0][4], largestword[0][5], largestword[0][6], session_data,
                                          session_sort, userid,
                                          dbname)
                    if back != None and len(back) != 0:
                        return recordbackdataforquestion(4, back, sessionid, cid, operation, '', '', dbname)
            # 疑问句跳转
            if ans == 'attitude5':
                back = question_jump(sessionid, dbname, cmpid, askid, cid, text,
                                     serviceid, session_data, session_sort, userid)
                web_logger.info('态度跳转--ans--attitude5 cid:%s back:%s', cid, back)

                if back != None and len(back) != 0:
                    back_data = ()
                    for index, value in enumerate(back):
                        if index == 2:
                            back_data += (11,)
                        else:
                            back_data += (value,)
                    return recordbackdataforquestion(4, back_data, sessionid, cid, operation, '', '', dbname)
            if memcachcon.if_exist(str(dbname) + 'Jumpprocesses' + str(cid)) != None:
                memcachcon.del_cach(str(dbname) + 'Jumpprocesses' + str(cid))
            back = allattitude(ans, cid, serviceid, sessionid, operation, askid, cmpid, wordslotid, session_data,
                               session_sort, userid, dbname, get_digits)
            if back != None and len(back) != 0:
                return back
        elif memcachcon.if_exist(str(dbname) + 'Jumpprocesses' + str(cid)) != None and askid != "" and str(
                operation) != '5':
            Jumpprocessesnum = memcachcon.if_exist(str(dbname) + 'Jumpprocesses' + str(cid))
            memcachcon.del_cach(str(dbname) + 'Jumpprocesses' + str(cid))
            web_logger.info('问题库跳转进来了 cid:%s Jumpprocessesnum:%s', cid, Jumpprocessesnum)
            return juntohoodel(Jumpprocessesnum, cid, sessionid, operation, cmpid, 4, 5, session_data, session_sort,
                               userid, dbname)

        elif ans[:7] == 'notnext' and askid != "":
            # 疑问句跳转
            back = question_jump(sessionid, dbname, cmpid, askid, cid, text, serviceid, session_data, session_sort,
                                 userid)
            if back != None and len(back) != 0:
                back_data = ()
                for index, value in enumerate(back):
                    if index == 2:
                        back_data += (11,)
                    else:
                        back_data += (value,)
                return recordbackdataforquestion(4, back_data, sessionid, cid, operation, '',
                                                 '', dbname)
            if operation == '5':
                tupledata = (
                    '打断忽略', 1, 3, '0', 'open', askid, '', '', '4', '1', '', '', wordslotid, '', '', '4', '1',
                    session_data,
                    session_sort)  # 557788
                return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)
            closecount_data = memcachcon.if_exist(str(dbname) + 'closecount' + str(cid))
            if closecount_data != None:
                bye = selcommon(cmpid, serviceid, closecount_data, 'bye', dbname, cid)
                if len(bye) != 0:
                    back = globalvariable(bye[0][0], bye[0][1], bye[0][2], bye[0][3], cid, cmpid, serviceid, askid,
                                          'bye', '', bye[0][4], bye[0][5], bye[0][6], session_data, session_sort,
                                          userid, dbname)
                    if back != None and len(back) != 0:
                        return recordbackdataforquestion(len(back), back, sessionid, cid, operation, '0', '', dbname)
            intentionback = selnotquestionaskintention(cid, askid, sessionid, operation, cmpid, session_data,
                                                       session_sort, dbname)
            if intentionback != None:
                return intentionback

            HoodleMobile = ()
            if memcachcon.if_exist(str(dbname) + 'sendmessage' + str(cid)) != None and askid != "":
                memcachcon.del_cach(str(dbname) + 'sendmessage' + str(cid))
                HoodleMobile = selHoodleMobileadressinterrupt(askid, dbname, cid)
                web_logger.info('sendmessage cid:%s HoodleMobile:%s', cid, HoodleMobile)
            if len(HoodleMobile) != 0:
                return skipquestion(HoodleMobile, cid, '', 'no_match', cmpid, '', session_data, session_sort, userid,
                                    dbname)
            memcachcon.set_cach(str(dbname) + 'notnextandbegin' + str(cid), 1)
            if memcachcon.if_exist(str(dbname) + 'notnextagain' + str(cid)) == None:
                memcachcon.set_cach(str(dbname) + 'notnextagain' + str(cid), 1)
            else:
                memcachcon.add_num(str(dbname) + 'notnextagain' + str(cid))

            notnextagain_data = memcachcon.if_exist(str(dbname) + 'notnextagain' + str(cid))
            if notnextagain_data == None:
                notnextagain_data = 1

            no_match = unknowphone(askid, cmpid, serviceid, operation, sessionid, cid, notnextagain_data, session_data,
                                   session_sort, userid, dbname)
            if no_match != None and len(no_match) != 0:
                return no_match

        elif ans[:5] == 'skill':
            skill = skillskip(ans[5:], '', cid, askid, session_data, session_sort, dbname)
            if len(skill) != 0:
                return skill

    if ans[:8] == 'attitude':
        return endsentences(cmpid, serviceid, sessionid, cid, operation, '1', ans[8:], session_data, session_sort,
                            userid, dbname)
    return endsentences(cmpid, serviceid, sessionid, cid, operation, '', '', session_data, session_sort, userid, dbname)


# 判断是否疑问句跳转
def question_jump(sessionid, dbname, cmpid, askid, cid, text, serviceid, session_data, session_sort, userid):
    answerFlag = questions_thread(sessionid, 3, '', '', dbname, cid, text)
    back = ''
    if answerFlag == 11:
        insertquestion = ThreadWithReturnValue(target=insertbackrecordphone,
                                               args=(
                                                   sessionid, 1, 11, '',
                                                   '', dbname, cid))
        insertquestion.start()

        whole_question = selcommon(cmpid, serviceid, 1, 'question', dbname, cid)
        if len(whole_question) != 0:
            back = globalvariable(whole_question[0][0], whole_question[0][1],
                                  whole_question[0][2], whole_question[0][3], cid, cmpid,
                                  serviceid,
                                  askid, 'question', '', whole_question[0][4],
                                  whole_question[0][5], whole_question[0][6],
                                  session_data,
                                  session_sort, userid, dbname)
    return back


# 技能跳转
def skillskip(skillid, wordslotid, cid, askid, session_data, session_sort, dbname):
    # 查询技能
    skill = selskill(skillid, wordslotid, dbname, cid)
    # print('skill',skill)
    if len(skill) != 0:
        # 插入要采集记录
        insertcollection(cid, skill[0][0], dbname)
        # l.wordslotid,l.content,l.type,l.collecttype
        return (skill[0][1], 1 if skill[0][2] == 1 else 9, 1, 0, 'open', askid, '', '', '5' if skill[0][3] == 1 else '',
                skill[0][4], '', '0', skill[0][0], '', '', '', '', session_data, session_sort)  # 557788


# 态度跳转
@time_statistic(1, 'cid')
def allattitude(ans, cid, serviceid, sessionid, operation, askid, cmpid, wordslotid, session_data, session_sort,
                userid, dbname, get_digits=None):
    if str(ans[8:]) == '6' or str(ans[8:]) == '7' or str(ans[8:]) == '11':
        if str(ans[8:]) == '11':
            if memcachcon.if_exist(str(dbname) + 'awaitcount' + str(cid)) == None:
                memcachcon.set_cach(str(dbname) + 'awaitcount' + str(cid), 1)
        back = specailanswerattitue(cmpid, serviceid, cid, sessionid, operation, askid, ans[8:], session_data,
                                    session_sort, userid, dbname)
        if back != None and len(back) != 0:
            return back
    else:
        intentionback = selnotquestionaskintention(cid, askid, sessionid, operation, cmpid, session_data, session_sort,
                                                   dbname)
        web_logger.info('cid:%s operation:%s intentionback:%s', cid, operation, intentionback)
        if intentionback != None:
            return intentionback
        if memcachcon.if_exist(str(dbname) + 'answercach' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'answercach' + str(cid))
            # 如果是肯定有其他走其他 没其他走肯定
            if ans == 'attitude1':
                # 查询是否有其他态度
                attitudecount = selotherattitude(dbname, cid, askid)
                if attitudecount > 0:
                    ans = 'attitude5'

        if memcachcon.if_exist(str(dbname) + 'notnextandbegin' + str(cid)) != None:
            memcachcon.del_cach(str(dbname) + 'notnextandbegin' + str(cid))

        back = haveattitude(cid, ans, cmpid, askid, serviceid, operation, wordslotid, sessionid, session_data,
                            session_sort, userid, dbname, get_digits)
        if back != None and len(back) != 0:
            return back


# 查询是否有其他的态度
def selotherattitude(dbname, cid, HoodleMobileid):
    sql = "SELECT count(*) from zt_know_hoodlemobile_answer a where a.HoodleMobileid='" + str(
        HoodleMobileid) + "' and a.attitude=5"
    attitudecount = conn.mysql_selrowid(sql, dbname, cid)
    return attitudecount


# 跳转问题
@time_statistic(1, 'cid')
def skipquestion(HoodleMobile, cid, closeresult, attituescence, cmpid, attitue, session_data, session_sort, userid,
                 dbname):
    instructid = ''
    answerflag = 1
    web_logger.info('问题跳转 cid:%s HoodleMobile:%s', cid, HoodleMobile)
    # HoodleMobileadress = str(HoodleMobile[0][0])
    # 插入调用记录
    insertask(cmpid, HoodleMobile[0][1], cid, HoodleMobile[0][3], session_data, session_sort, dbname)
    if HoodleMobile[0][8] and HoodleMobile[0][9]:
        memcachcon.set_cach(str(conn.basedbname) + 'questionnairetype' + str(HoodleMobile[0][1]) + str(cid),
                            HoodleMobile[0][8])
        memcachcon.set_cach(str(conn.basedbname) + 'matchidlist' + str(HoodleMobile[0][1]) + str(cid),
                            HoodleMobile[0][9])
    # 插入场景
    insertsessionsence(cid, HoodleMobile[0][3], session_data, session_sort, dbname)
    # if HoodleMobile[0][4] == 2:
    #     HoodleMobileadress = backvariant(HoodleMobile[0][0], cid, HoodleMobile[0][2], cmpid, userid)
    if attituescence == "await":
        instructid = '2'
    if attituescence == "no_match" or str(attitue) == '5':
        answerflag = 3

    if closeresult != "" and HoodleMobile[0][3] == 4:
        # 更新挂机原因
        memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), closeresult)
        # updatacloseresult(cid,closeresult)
    type = ''
    num = ''

    if attitue == "4":
        type = 4
        num = attituescence
    elif attituescence != "":
        type = 2
        if attituescence == "no_word":
            num = 1
        elif attituescence == "no_match":
            num = 2
        elif attituescence == "no_input":
            num = 3
        elif attituescence == "busy":
            num = 4
        elif attituescence == "dirty":
            num = 5
        elif attituescence == "to_much":
            num = 6
        elif attituescence == "repeat":
            num = 7
        elif attituescence == "break":
            num = 8
        elif attituescence == "transform":
            num = 9
        elif attituescence == "send_note":
            num = 10
        elif attituescence == "refuse":
            num = 11
        elif attituescence == "await":
            num = 12
        elif attituescence == "awaken":
            num = 13
        elif attituescence == "hello":
            num = 14
        elif attituescence == "bye":
            num = 15
        elif attituescence == "offline":
            num = 16
        elif attituescence == "handover":
            num = 17
        elif attituescence == "largestword":
            num = 18
        elif attituescence == "question":
            num = 19
        else:
            pass

    elif attitue != "":
        type = 1
        ium = attitue

    # backtype = HoodleMobile[0][2]
    # backremark = ""

    # if HoodleMobile[0][4] == 2:  # 语音变量
    #
    #     backtext = backvariant(HoodleMobile[0][5], cid, 1, cmpid, userid)
    #
    #     if HoodleMobile[0][2] == 2:
    #         backtype = 11
    #         backremark = backtext
    #     elif HoodleMobile[0][2] == 3:
    #         backtype = 11
    #         backremark = backvariant(HoodleMobile[0][0], cid, 1, cmpid, userid)  # 如果是文本是按1来，如果是语音的话按2来
    #         HoodleMobileadress = backvariant(HoodleMobile[0][7], cid, 2, cmpid, userid)
    #
    #     return (HoodleMobileadress, backtype, answerflag, '', 'close' if HoodleMobile[0][3] == 4 else 'open',
    #             HoodleMobile[0][1], '', '', instructid, backremark, '', HoodleMobile[0][6], '', '', '', type, num,
    #             session_data, session_sort)  # 557788
    # if HoodleMobile[0][2] == 2:
    #     backtype = 9
    #     backremark = HoodleMobile[0][5]
    # elif HoodleMobile[0][2] == 3:
    #     backtype = 9
    #     backremark = HoodleMobileadress
    #     HoodleMobileadress = HoodleMobile[0][7]
    backchangedata = changebackdataforTTS(HoodleMobile[0][4], HoodleMobile[0][2], HoodleMobile[0][0],
                                          HoodleMobile[0][5], HoodleMobile[0][7], cmpid, userid, cid, dbname)
    return (
        backchangedata['backtext'], backchangedata['backtype'], answerflag, '',
        'close' if HoodleMobile[0][3] == 4 else 'open', HoodleMobile[0][1],
        '', '', instructid, backchangedata['backremark'], '', HoodleMobile[0][6], '', '', '', type, num, session_data,
        session_sort)  # 557788


@time_statistic(0, 'cid')
def haveattitude(cid, ans, cmpid, askid, serviceid, operation, wordslotid, sessionid, session_data, session_sort,
                 userid, dbname, get_digits=None):
    """

    :param cid:  会话编码
    :param ans:  学习的答案
    :param cmpid:  公司编码
    :param askid:  主动提问编码
    :param serviceid:  服务编码
    :param operation:  操作（1：创建新会话 2：终止通话 3：正常提问  4：久不应答  5:用户打断 6：保存聊天记录 7.电话训练机器人 8未接原因 ）
    :param wordslotid:
    :param sessionid:
    :param session_data:  聊天编码
    :param session_sort:  会话顺序
    :return:
    """
    instructid = ''
    # #查询答案对应的下一轮
    ansdata = ans[8:]  # attitude + 1
    web_logger.info('cid:%s operation:%s ans:%s cmpid:%s askid:%s serviceid:%s wordslotid:%s sessionid:%s session_data:%s session_sort:%s userid:%s dbname:%s',
                    cid, operation, ans, cmpid, askid, serviceid, wordslotid, sessionid, session_data, session_sort, userid, dbname)

    extround = SelectAttribute1(ansdata, dbname, cid)
    web_logger.info('cid:%s extround:%s', cid, extround)
    if str(extround) == "2":

        # 查询态度分支
        branchattitude = SelectAttribute(ansdata, userid, askid, dbname, cid)

        if len(branchattitude) != 0:
            the_back = The_process_to_jump(branchattitude, cid, session_data, session_sort, cmpid, ansdata, serviceid,
                                           ans, askid, instructid, userid, dbname)
            if the_back != None:
                return the_back

    if ans[8:] != "":
        if operation == '5' and str(ans[8:]) == '5':  # 经过了用户打断。 1：创建新会话 2：终止通话 3：正常提问  4：久不应答  5:用户打断
            tupledata = (
                '打断忽略', 1, 1 if str(ansdata) != '5' else 3, '0', 'open', askid, '', '', '4', '1', '', '', wordslotid,
                '',
                '', '4', '1', session_data, session_sort)  # 557788
            return recordbackdataforquestion(4, tupledata, sessionid, cid, operation, '', '', dbname)  # 转换编码格式
        sql_value_attrid = "select l.attrid from zt_sale_data s ,zt_customer_attr_link l where s.saleid='" + str(
            cid) + "' and l.tmcustid = s.temporarycustomerid"
        value_attrid = conn.mysql_selrowid(sql_value_attrid, dbname, cid)
        sql_attitudeids = "SELECT attitudeids FROM zt_know_hoodlemobile_answer_link WHERE serviceid='" + str(
            serviceid) + "'"
        attitudeids = conn.mysql_selrowid(sql_attitudeids, dbname, cid)
        print('attitudeids', attitudeids, type(attitudeids), 'len', len(attitudeids), type(len(attitudeids)))
        if value_attrid != "" and len(attitudeids) != 0:
            count = 0
            count += 1
            print('count', count)
            adlist = ['4', '8', '9', '10', '1', '2', '3', '4', '5']
            print('session_sort', session_sort)
            print('len', type(extround), 'extround:', extround, 'len:', len(str(extround)))
            if ans[8:] in adlist:
                if int(session_sort) < 3:
                    extround = selnextround1(ans[8:], askid, dbname, cid)
                else:
                    extround = selnextround(ans[8:], askid, dbname, cid)
                print('加了1的')
            else:
                extround = selnextround(ans[8:], askid, dbname, cid)
                print('否定这个')
            print('是第一个')
        else:
            extround = selnextround(ans[8:], askid, dbname, cid)
            print('是第二个')
        print("**********************************************查询extround*****************************")
        print(extround)
        print("*******************************************")
        ifinvite = selifinvite(askid, dbname, cid)  # 查询出邀约次数
        # print("***********************ifinvite***********************************")
        # print(ifinvite)
        # print("****************************************************")
        # 多次拒接
        if str(ans[8:]) == '3':  # attitude之后的数据为3 ， 肯定.否定.拒绝(接).特殊.其它
            if memcachcon.if_exist(str(dbname) + 'refusecount' + str(cid)) == None:
                memcachcon.set_cach(str(dbname) + 'refusecount' + str(cid), 1)
            else:
                memcachcon.add_num(str(dbname) + 'refusecount' + str(cid))

            # 查询企业设置的拒接次数
            rejectcount = selrejectcount(cmpid, serviceid, dbname, cid)  # 查询数据库中企业的拒接次数，数据库中目前都是2

            refusecount_data = memcachcon.if_exist(str(dbname) + 'refusecount' + str(cid))

            web_logger.info('cid:%s rejectcount:%s refusecount_data:%s', cid, rejectcount, refusecount_data)
            if refusecount_data != None and str(refusecount_data) == str(rejectcount):
                refusedata = selcommon(cmpid, serviceid, 1, 'refuse', dbname, cid)
                if len(refusedata) != 0:
                    back = globalvariable(refusedata[0][0], refusedata[0][1], refusedata[0][2], refusedata[0][3], cid,
                                          cmpid, serviceid, askid, 'refuse', '', refusedata[0][4], refusedata[0][5],
                                          refusedata[0][6], session_data, session_sort, userid, dbname)
                    if back != None and len(back) != 0:
                        web_logger.info('refuse 拒接次数多次 back:%s ', back)
                        memcachcon.del_cach(str(dbname) + 'refusecount' + str(cid))
                        return back
        if str(ifinvite) != '0':
            att = str(ans[8:])
            """
            记录是否邀约成功
            """
            if att == '1' or att == '2' or att == '3':
                if str(att) == '3':
                    att = '2'
                # 是否邀约成功
                memcachcon.set_cach(str(dbname) + 'isagree' + str(cid), att)

                # 更新挂机原因
                memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), '7' if att == '2' else '10')

        # 插入答案
        updateask(cmpid, cid, askid, ans[8:], session_data, session_sort, dbname)
        # 查询是否需要转人工
        transfer = Judgmenttransfer(cid, cmpid, serviceid, dbname)
        print('查询是否需要转人工transfer--robotsql', transfer)
        if len(transfer) != 0:
            if transfer[0][0] >= 1:

                if str(transfer[0][2]) == '2':
                    return Turnphone(cmpid, serviceid, transfer[0][1], cid, askid, '1', ans[8:], session_data,
                                     session_sort, userid, dbname)
                else:
                    return Turntotheartificial(cmpid, serviceid, transfer[0][1], cid, askid, '1', ans[8:], session_data,
                                               session_sort, userid, dbname)
        print('extround------len', extround, str(len(extround)))
        if str(len(extround)) != '0':
            print(
                '1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111')
            HoodleMobileAnswerid = extround[0][4]
            print('---HoodleMobileAnswerid--', HoodleMobileAnswerid, '--extround--:', extround)
            # 查询态度分支(标签)  6
            branchattitude = sel_branch_attitude(HoodleMobileAnswerid, dbname, cid)
            # 查询分享机器人分支
            htypeid = memcachcon.if_exist(str(dbname) + 'sharetype' + str(cid))
            # if htypeid:
            #     branchattitude = sel_branch_attitude(HoodleMobileAnswerid, dbname, cid)
            if len(branchattitude) != 0:
                for brancha in branchattitude:
                    #  print(brancha)
                    attridbranchalist = str(brancha[4])
                    the_htypeid = str(brancha[5])
                    # print(the_htypeid,htypeid,attridbranchalist)
                    if the_htypeid and htypeid and htypeid == the_htypeid and attridbranchalist:  # 2个条件相等
                        # 查询条件是否都存在
                        #  print('XXXXXXX333')
                        if attridbranchalist:
                            count = sel_conditions(attridbranchalist, cid, dbname)

                            if (int(attridbranchalist.count(',')) + 1) == int(count):
                                the_back = The_process_to_jump(brancha, cid, session_data, session_sort, cmpid, ansdata,
                                                               serviceid, ans, askid, instructid, userid, dbname)
                                if the_back != None:
                                    return the_back
                    elif the_htypeid and htypeid and htypeid == the_htypeid and attridbranchalist == '':  # 主流程相等
                        #  print('ZZZZ333',htypeid,the_htypeid)
                        the_back = The_process_to_jump(brancha, cid, session_data, session_sort, cmpid, ansdata,
                                                       serviceid, ans, askid, instructid, userid, dbname)
                        if the_back != None:
                            return the_back
                    elif attridbranchalist and the_htypeid == "":  #
                        #  print('QQQQ333')
                        if attridbranchalist:
                            count = sel_conditions(attridbranchalist, cid, dbname)

                            if (int(attridbranchalist.count(',')) + 1) == int(count):
                                the_back = The_process_to_jump(brancha, cid, session_data, session_sort, cmpid, ansdata,
                                                               serviceid, ans, askid, instructid, userid, dbname)
                                if the_back != None:
                                    return the_back

            print('ttttttttttttttttttttttttttttttttttttttttttttttttttttttt')
            the_back = The_process_to_jump(extround[0], cid, session_data, session_sort, cmpid, ansdata, serviceid, ans,
                                           askid, instructid, userid, dbname, get_digits)
            print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^the_back^^^^^^^^^^^^^^^^^^^^^^")
            print(the_back)
            print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
            if the_back != None:
                return the_back


# 确认态度并跳转
@time_statistic(1, 'cid')
def The_process_to_jump(extround, cid, session_data, session_sort, cmpid, ansdata, serviceid, ans, askid, instructid,
                        userid, dbname, get_digits=None):
    web_logger.info('cid:%s extround:%s session_data:%s session_sort:%s cmpid:%s ansdata:%s serviceid:%s ans:%s askid:%s instructid:%s userid:%s dbname:%s',
                    cid, extround, session_data, session_sort, cmpid, ansdata, serviceid, ans, askid, instructid, userid, dbname)
    if extround[3] != None and extround[3] != '':
        tmcustid = seltmcustid(cid, dbname)  # 通过会话编码查到t.tmcustid
        attridlist = str(extround[3]).split(',')  #
        for attrid in attridlist:
            insert_zt_customer_attr_link(tmcustid, cid, session_data, session_sort,
                                         attrid, dbname)  # 向zt_customer_attr_link插入数据

    if str(extround[0]) == "1":  # 1问题跳转
        # 插入会话场景
        """
    1问题跳转 2场景跳转 3转人工 4发短信 5流程继续 6转号码 7交接
        """
        HoodleMobile = selHoodleMobileadress(extround[1], dbname, cid)
        if HoodleMobile[0][7] and HoodleMobile[0][8]:
            memcachcon.set_cach(str(conn.basedbname) + 'questionnairetype' + str(extround[1]) + str(cid),
                                HoodleMobile[0][7])
            memcachcon.set_cach(str(conn.basedbname) + 'matchidlist' + str(extround[1]) + str(cid), HoodleMobile[0][8])

        # 插入主动提问问题
        insertask(cmpid, extround[1], cid, HoodleMobile[0][1], session_data, session_sort, dbname)

        backchagedata = changebackdataforTTS(HoodleMobile[0][3], HoodleMobile[0][2], HoodleMobile[0][0],
                                             HoodleMobile[0][4], HoodleMobile[0][6], cmpid, userid, cid, dbname)
        return (
            backchagedata['backtext'], backchagedata['backtype'], 1 if str(ansdata) != '5' else 3, 0,
            'open' if HoodleMobile[0][1] != 4 else 'close', extround[1], '', '',
            instructid,
            backchagedata['backremark'], '', HoodleMobile[0][5], '', '', '', '1', ans[8:], session_data,
            session_sort)  # 557788

    #
    elif str(extround[0]) == "2":

        if str(extround[1]) != '4':
            return skipscene(extround[1], cmpid, serviceid, cid, '', '', '1', ans[8:], session_data, session_sort,
                             userid, dbname)
    elif str(extround[0]) == "3":

        # 查询转接语
        return Turntotheartificial(cmpid, serviceid, extround[1], cid, askid, '1', ans[8:], session_data,
                                   session_sort, userid, dbname)

    elif str(extround[0]) == "4":
        return sendmessagecommon(cmpid, serviceid, askid, extround[1], cid, '1', ans[8:], session_data, session_sort,
                                 userid, dbname)
    elif str(extround[0]) == "5":

        return continueline(cid, cmpid, serviceid, askid, ans[8:], session_data, session_sort, '', userid, dbname)
    elif str(extround[0]) == "6":
        phone = extround[1]
        if extround[6] != None:
            the_new_phone = sel_sphone(cid, extround[6])
            if the_new_phone != "":
                phone = the_new_phone
        return Turnphone(cmpid, serviceid, phone, cid, askid, '1', ans[8:], session_data, session_sort, userid, dbname)
    elif str(extround[0]) == "7":  # 交接
        if memcachcon.if_exist(str(dbname) + 'handover' + str(cid)) != None:
            memcachcon.add_num(str(dbname) + 'handover' + str(cid))
        else:
            memcachcon.set_cach(str(dbname) + 'handover' + str(cid), 1)

        handover_data = memcachcon.if_exist(str(dbname) + 'handover' + str(cid))
        handoverdata = selcommon(cmpid, serviceid, handover_data, 'handover', dbname, cid)
        # a.content,a.ctype,a.text,a.type,a.intentionid,a.isend,a.voxfile
        memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), 9)
        memcachcon.set_cach(str(dbname) + 'istransfer' + str(cid), 1)
        # print(66666666666666666666666666666,memcachcon.if_exist(str(dbname)+'istransfer' + str(cid)))
        backtype = 1
        HoodleMobileadress = ''
        backremark = ''

        if handoverdata != None and len(handoverdata) != 0:
            backchagedata = changebackdataforTTS(1, handoverdata[0][1], handoverdata[0][0],
                                                 handoverdata[0][2], handoverdata[0][6], cmpid, userid, cid, dbname)
            backtype = backchagedata['backtype']
            HoodleMobileadress = backchagedata['backtext']
            backremark = backchagedata['backremark']
        return (
            HoodleMobileadress, backtype, 1, '', 'open', '', '', '', '6', backremark, '', '', '', '', '', '1', ans[8:],
            session_data, session_sort)
    elif str(extround[0]) in ('8', '9', '10',):
        content_map = {
            '8': '身份证采集',
            '9': '金融数额采集',
            '10': '电话号码采集',
        }
        get_digits_map = {
            '8': '1',
            '9': '2',
            '10': '3', }
        typedata = ''
        content = content_map[str(extround[0])]
        backanswer = "叮"
        attitude_id = ans[8:]  # ans 是态度 = attitude3
        HoodleMobileAnswerid = extround[4]
        data = get_collect_btn_memo(HoodleMobileAnswerid, dbname, cid)
        backtype = '9'
        if data:
            content_type = data[1]
            if content_type == 1:
                content = data[2]
                backanswer = data[2]
                backanswer = get_TTS_voice_address(conn.TTSIP, backanswer, cid, 0.5, 0.6, '', '1', 0, '')
            else:
                content = data[3]
                backanswer = data[2]
        web_logger.info('cid:%s attitude_id:%s HoodleMobileAnswerid:%s data:%s content:%s backanswer:%s', cid, attitude_id, HoodleMobileAnswerid, data,content,backanswer)
        hoodlemobile_id = get_next_hoodlemobile_id(attitude_id, HoodleMobileAnswerid, dbname, cid)

        if get_digits in ('1', '2', '3', '4',):
            backinfo = continueline(cid, cmpid, serviceid, askid, ans[8:], session_data, session_sort, '', userid,
                                    dbname)
            return backinfo
        get_digits = get_digits_map[str(extround[0])]
        extend_data = {'max_count': '', ' max_digits': '', 'min_digits': '', 'timeout_digits': '', 'error_memo': '',
                       'get_digits': get_digits, 'backtype': backtype, 'backanswer': backanswer}

        # backinfo 顺序说明  ----- 为未知  [] 为可选
        # backtext,typedata,code,interrupt,conversation,askid,serviceid,attach,instructid,memo,-------,collectid,phone,-----,type,-----,session_data,session_sort,[extend_data]
        backinfo = ('', typedata, 1, '0', 'open', hoodlemobile_id, '', '', '', content, '', '0', '', '', '', '', '',
                    session_data,
                    session_sort, extend_data)
        print('backinfo', backinfo)
        return backinfo


@time_statistic(7, 'cid')
def changebackdataforTTS(qtype, Ttype, HoodleMobiledress, remake, voflie, cmpid, userid, cid, dbname):
    print('---changebackdataforTTS---Ttype', Ttype)
    backtype = 1
    backtext = HoodleMobiledress
    backremark = remake
    print(qtype, Ttype, HoodleMobiledress, remake, voflie, cmpid, userid, cid)
    if qtype == 2:  # 1：常量 2：变量
        # 1：文本2：语音3：TTS转语音

        if Ttype == 3:  # TTS语音变量
            backtype = 11
            backtext = backvariant(voflie, cid, 2, cmpid, userid, dbname)
            backremark = backvariant(HoodleMobiledress, cid, 1, cmpid, userid, dbname)
        elif Ttype == 1:  # 文本变量
            backtext = backvariant(HoodleMobiledress, cid, 1, cmpid, userid, dbname)
        elif Ttype == 2:  # 语音变量
            backtype = 11
            backtext = backvariant(HoodleMobiledress, cid, 2, cmpid, userid, dbname)
            backremark = backvariant(remake, cid, 1, cmpid, userid, dbname)
    else:
        if Ttype == 2 or Ttype == 3:
            backtype = 9
            if Ttype == 3:
                backtext = voflie
                backremark = HoodleMobiledress
    return {'backtype': backtype, 'backtext': backtext, 'backremark': backremark}


# 继续流程
def continueline(cid, cmpid, serviceid, askid, attitue, session_data, session_sort, attituescence, userid, dbname):
    lastask = selLastask(cid, serviceid, dbname)

    if lastask != '' and lastask != None:
        HoodleMobile = notanswernethoodlemobile(cmpid, serviceid, lastask, cid, dbname)
        if len(HoodleMobile) != 0:
            return skipquestion(HoodleMobile, cid, '', attituescence, cmpid, attitue, session_data, session_sort,
                                userid, dbname)


# 发短信
def sendmessagecommon(cmpid, serviceid, askid, modelid, cid, type, num, session_data, session_sort, userid, dbname):
    # 查询发短信提示selnoteanwer
    # noteanwer = selnoteanswerback(cmpid,serviceid)
    noteanwer = selcommon(cmpid, serviceid, 1, 'send_note', dbname, cid)
    url = message + '/open/sendnote?saleid=' + str(cid) + '&modelid=' + str(modelid) + ''
    web_logger.info('短信接口 cid:%s url:%s', cid, url)
    req = rs.get(url)
    data = req.json()
    HoodleMobile = notanswernethoodlemobile(cmpid, serviceid, askid, cid, dbname)
    web_logger.info('短信接口返回值 cid:%s data:%s', cid, data)
    if data['code'] == 10000:
        # HoodleMobileadress = noteanwer[0][0]
        # 没有设计下一问题
        memcachcon.set_cach(str(dbname) + 'sendmessage' + str(cid), 1)

        backchangedata = changebackdataforTTS(1, noteanwer[0][1], noteanwer[0][0],
                                              noteanwer[0][2], noteanwer[0][6], cmpid, userid, cid, dbname)
        HoodleMobileadress = backchangedata['backtext']
        backtype = backchangedata['backtype']
        backremark = backchangedata['backremark']
        return (
            HoodleMobileadress, backtype, 1, '', 'open', HoodleMobile[0][1], '', '', '', backremark, '', '', '', '', '',
            type, num, session_data, session_sort)  # 557788
    else:
        return (
            '发送短信失败', 1, 1, '', 'open', HoodleMobile[0][1], '', '', '', '', '', '', '', '', '', type, num, session_data,
            session_sort)  # 557788


# 转人工
def Turntotheartificial(cmpid, serviceid, Turnserviceid, cid, askid, type, num, session_data, session_sort, userid,
                        dbname):
    transforanwer = selcommon(cmpid, serviceid, 1, 'transform', dbname, cid)
    print('走了这个函数')
    # (('/robotvoice/20181225/20181225162339_803.wav', 2, '\xa0电话正在转接中，请稍等', 5, None, None, None),)
    # 判断是否有客服在线
    # transforanwer = (('/robotvoice/20181225/20181225162339_803.wav', 2, '\xa0电话正在转接中，请稍等', 5, None, None, None),)
    ifonline = redisconn.selkefuonline(cmpid, Turnserviceid, dbname)
    web_logger.info('cid:%s serviceid:%s ifonline:%s', cid, serviceid, ifonline)
    if ifonline == 1:
        # 更新已转人工
        memcachcon.set_cach(str(dbname) + 'istransfer' + str(cid), 1)
        istransfer = memcachcon.if_exist(str(dbname) + 'istransfer' + str(cid))
        web_logger.info('更新已转人工 cid:%s serviceid:%s istransfer:%s', cid, serviceid, istransfer)
        backanswer = ''
        backtype = 1
        backremark = ""

        if transforanwer != None and len(transforanwer) != 0:
            backanswer = transforanwer[0][0]
            backchangedata = changebackdataforTTS(1, transforanwer[0][1], transforanwer[0][0],
                                                  transforanwer[0][2], transforanwer[0][6], cmpid, userid, cid, dbname)
            backanswer = backchangedata['backtext']
            backtype = backchangedata['backtype']
            backremark = backchangedata['backremark']
        return (
            backanswer, backtype, 1, '', 'open', askid, Turnserviceid, '', '1', backremark, '', '', '', '', '', type,
            num,
            session_data, session_sort)  # 557788

    else:
        offline = selcommon(cmpid, serviceid, 1, 'offline', dbname, cid)
        if len(offline) != 0:
            back = globalvariable(offline[0][0], offline[0][1], offline[0][2], offline[0][3], cid, cmpid, serviceid,
                                  askid, 'offline', '', offline[0][4], offline[0][5], offline[0][6], session_data,
                                  session_sort, userid, dbname)
            if back != None and len(back) != 0:
                return back


# print(Turntotheartificial('289', '5492', '7508', '456683791', '39467', '', '', '', '', '','kefu7'))
# transforanwer =(('/robotvoice/20181225/20181225162339_803.wav', 2, '\xa0电话正在转接中，请稍等', 5, None, None, None),)
# print(changebackdataforTTS(1, transforanwer[0][1], transforanwer[0][0],
#                                                   transforanwer[0][2], transforanwer[0][6], 289, '', 1,'kefu7'))
# 转号码
def Turnphone(cmpid, serviceid, Turnnum, cid, askid, type, num, session_data, session_sort, userid, dbname):
    transforanwer = selcommon(cmpid, serviceid, 1, 'transform', dbname, cid)
    # 更新挂机原因
    # a.content,a.ctype,a.text,a.type,a.intentionid,a.isend,a.voxfile
    # memcachcon.set_cach(str(dbname)+'closeresult' + str(cid), 9)

    # 是否转人工
    memcachcon.set_cach(str(dbname) + 'istransfer' + str(cid), 1)
    backtext = ''
    backtype = 1
    backmark = ''  # and  len(transforanwer[0][3]) == 5
    if transforanwer != None and len(transforanwer) != 0:
        backchangedata = changebackdataforTTS(1, transforanwer[0][1], transforanwer[0][0],
                                              transforanwer[0][2], transforanwer[0][6], cmpid, userid, cid, dbname)
        backtext = backchangedata['backtext']
        backtype = backchangedata['backtype']
        backmark = backchangedata['backremark']

    return (
        backtext, backtype, 1, '', 'open', askid, '', '', '1', backmark, '', '', '', Turnnum, '', type, num,
        session_data,
        session_sort)  # 557788


# 跳转场景
def skipscene(scene, cmpid, serviceid, cid, closeresult, attituescence, type, num, session_data, session_sort, userid,
              dbname):
    # h.HoodleMobileadress ,h.HoodleMobileid,h.type,h.qtype,h.remark,interrupt,h.voxfile,h.questionnairetype,h.matchidlist
    HoodleMobile = exchangescene(cmpid, scene, serviceid, dbname, cid)
    if HoodleMobile[0][7] and HoodleMobile[0][8]:
        memcachcon.set_cach(str(conn.basedbname) + 'questionnairetype' + str(HoodleMobile[0][1]) + str(cid),
                            HoodleMobile[0][7])
        memcachcon.set_cach(str(conn.basedbname) + 'matchidlist' + str(HoodleMobile[0][1]) + str(cid),
                            HoodleMobile[0][8])
    answerflag = 1
    # 插入主动提问问题
    insertask(cmpid, HoodleMobile[0][1], cid, scene, session_data, session_sort, dbname)
    backchangedata = changebackdataforTTS(HoodleMobile[0][3], HoodleMobile[0][2], HoodleMobile[0][0],
                                          HoodleMobile[0][4], HoodleMobile[0][6], cmpid, userid, cid, dbname)

    if attituescence == 'no_match':
        answerflag = 3
    if str(scene) == '4':
        if closeresult != "":
            # 更新挂机原因
            memcachcon.set_cach(str(dbname) + 'closeresult' + str(cid), closeresult)

    return (
        backchangedata['backtext'], backchangedata['backtype'], answerflag, '',
        'close' if str(scene) == '4' else 'open', HoodleMobile[0][1], '', '', '',
        backchangedata['backremark'], '', HoodleMobile[0][5], '', '', '', type, num, session_data,
        session_sort)  # 557788


# 分词后匹配回答
def choiceanswerB(text, cmpid, dbname, cid):
    # 分词
    questionlistid = participles(cmpid, text, dbname, cid)
    if questionlistid != None and questionlistid != 'null' and questionlistid != '':

        quelis = selWithquestion(questionlistid, cmpid, dbname, cid)
        if len(quelis) != 0:
            return ('不好意思吖，我还在学习中，目前不知道怎么回答这个问题呢(O_O)?', '刚刚在卖萌啦，我猜您是想问以下问题', quelis, 6, 11)


class ThreadWithReturnValue(Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, daemon=None):
        Thread.__init__(self, group, target, name, args, kwargs, daemon=daemon)

        self._return = None

    def run(self):
        if self._target is not None:
            self._return = self._target(*self._args, **self._kwargs)

    def join(self):
        Thread.join(self)
        return self._return


# 判断返回数据
def jugebackdata(size, tupledata, sessionid, cid, dbname):
    sufins = ""
    backcon = ()
    if size == 3:
        backcon = backtypeadd(1, cid, tupledata[1], tupledata[0], tupledata[2])
        sufins = insertbackrecord(sessionid, 1, tupledata[2], backcon, dbname, cid)
    elif size == 5:
        backcon = backtypequestionlistadd(1, cid, tupledata[3], tupledata[0], tupledata[1], tupledata[2], tupledata[4])
        sufins = insertbackrecord(sessionid, 1, tupledata[4], backcon, dbname, cid)
    elif size == 4:
        backcon = backtypeurladd(1, cid, tupledata[2], tupledata[0], tupledata[1], tupledata[3])
        sufins = insertbackrecord(sessionid, 1, tupledata[3], backcon, dbname, cid)
    if sufins != 1:
        return backtypeadd(0, cid, 1, "插入机器人回答错误！", '')
    return backcon


# 记录返回的数据编码phone
# def recordbackdataforquestion(size, tupledata, sessionid, cid, operation, hellorbye, waitingtime,dbname):
#    if tupledata[4] == 'close':
#        inserscore(cid, '', '')
#        delallcach(cid, '',dbname)
#        if memcachcon.if_exist(str(dbname)+'closecount' + str(cid)) == None:
#            memcachcon.set_cach(str(dbname)+'closecount' + str(cid), 1)
#        else:
#            memcachcon.add_num(str(dbname)+'closecount' + str(cid))
#
#    backcon = backtypeaddphone(1, cid, tupledata[1], tupledata[0], tupledata[2], tupledata[4], tupledata[5], operation,
#                               tupledata[6],
#                               tupledata[7], tupledata[8], tupledata[9], '',
#                               '0' if str(hellorbye) == '0' else tupledata[11],
#                               tupledata[12], tupledata[13], waitingtime, tupledata[15], tupledata[16], tupledata[17],
#                               tupledata[18],dbname)  # 557788
#    if str(tupledata[2])!='3':
#        insertbackrecordphone(sessionid, 1, tupledata[2], backcon, tupledata[3], dbname, cid)
#    else:
#        #启用新线程查询是否疑问句
#        threadA = ThreadWithReturnValue(target=questions_thread, args=(sessionid, tupledata[2], backcon, tupledata[3], dbname, cid))
#        threadA.start()
#    #sufins = insertbackrecordphone(sessionid, 1, tupledata[2], backcon, tupledata[3],dbname,cid)
#    # if sufins != 1:
#    #     return backtypeaddphone(0, cid, 1, "插入机器人回答错误！", '', '', '', operation, '', '', '', '', '', '', '', '', '', '',
#    #                             '', tupledata[17], tupledata[18],dbname)  # 557788
#
#    return backcon

# 记录返回的数据编码phone
@time_statistic(3, 'cid')
def recordbackdataforquestion(size, tupledata, sessionid, cid, operation, hellorbye, waitingtime, dbname):
    if tupledata[4] == 'close':
        # inserscore(cid, '', '')
        delallcach(cid, '', dbname)
        if memcachcon.if_exist(str(dbname) + 'closecount' + str(cid)) == None:
            memcachcon.set_cach(str(dbname) + 'closecount' + str(cid), 1)
        else:
            memcachcon.add_num(str(dbname) + 'closecount' + str(cid))
    web_logger.info('cid:%s operation:%s tupledata:%s sessionid:%s hellorbye:%s waitingtime:%s',
                    cid, operation, tupledata, sessionid, hellorbye, waitingtime)
    backcon = backtypeaddphone(1, cid, tupledata[1], tupledata[0], tupledata[2], tupledata[4], tupledata[5], operation,
                               tupledata[6],
                               tupledata[7], tupledata[8], tupledata[9], '',
                               '0' if str(hellorbye) == '0' else tupledata[11],
                               tupledata[12], tupledata[13], waitingtime, tupledata[15], tupledata[16], tupledata[17],
                               tupledata[18], dbname)  # 557788
    if str(tupledata[2]) != '11':
        threadA = ThreadWithReturnValue(target=insertbackrecordphone,
                                        args=(sessionid, 1, tupledata[2], backcon, tupledata[3], dbname, cid))
        threadA.start()

    if isinstance(tupledata[-1], dict):
        backcon = json.loads(backcon)
        backcon.update(tupledata[-1])
        backcon = json.dumps(backcon)

    web_logger.info('cid:%s operation:%s backcon:%s', cid, operation, backcon)
    return backcon


# 查询疑问词
# def sel_questions_key(answertypeid, dbname, cid):
#    sql ="SELECT a.answer from zt_know_answerid a where a.state=1 and a.answertypeid='"+str(answertypeid)+"'"
#    question_key = conn.mysql_seldic(sql, dbname, cid)
#    return question_key
#
# def sel_questions_text(sessionid, dbname, cid):
#    sql ="SELECT c.contet from zy_rcustomerquestion c where c.sessionid='"+str(sessionid)+"';"
#    question_text = conn.mysql_selrowid(sql, dbname, cid)
#    return question_text
#
# def questions_thread(sessionid, answerFlag, backcon, answerid, dbname, cid):
#    questions_key = sel_questions_key(15, dbname, cid)
#    text = sel_questions_text(sessionid, dbname, cid)
#    if text !="":
#        for question in questions_key:
#            #正则匹配
#            try:
#                pipe_word = re.compile(question["answer"])
#                worklist = re.findall(pipe_word, text)
#                print('worklist',worklist)
#                if len(worklist)!=0:
#
#                    answerFlag = 11
#            except:
#                writetxt('robottxt',
#                              'questions_thread   ' + str(datetime.datetime.now()) + ' ' + str(cid) + ' ' + str(
#                                  question["answer"]))
#    insertbackrecordphone(sessionid, 1, answerFlag, backcon, answerid, dbname, cid)
#


# 查询疑问词
def sel_questions_key(answertypeid, dbname, cid):
    sql = "SELECT a.answer from zt_know_answerid a where a.state=1 and a.answertypeid='" + str(answertypeid) + "'"
    question_key = conn.mysql_seldic(sql, dbname, cid)
    return question_key


def sel_questions_text(sessionid, dbname, cid):
    sql = "SELECT c.contet from zy_rcustomerquestion c where c.sessionid='" + str(sessionid) + "';"
    question_text = conn.mysql_selrowid(sql, dbname, cid)
    return question_text


def questions_thread(sessionid, answerFlag, backcon, answerid, dbname, cid, text):
    questions_key = sel_questions_key(15, dbname, cid)
    # text = sel_questions_text(sessionid, dbname, cid)
    answerFlag = 3
    if text != "":
        for question in questions_key:
            # 正则匹配
            try:
                pipe_word = re.compile(question["answer"])
                worklist = re.findall(pipe_word, text)
                print('worklist', worklist)
                if len(worklist) != 0:
                    web_logger.info('cid:%s answer:%s worklist:%s', cid, question["answer"], worklist)
                    answerFlag = 11
            except:
                web_logger.info('cid:%s answer:%s', cid, question["answer"])
    return answerFlag


# 记录返回的数据编码不用存储到数据库
@time_statistic(3, 'cid')
def recordbackdataforquestionnotinsert(size, tupledata, sessionid, cid, operation, hellorbye, waitingtime, dbname):
    backcon = backtypeaddphone(1, cid, tupledata[1], tupledata[0], tupledata[2], tupledata[4], tupledata[5], operation,
                               tupledata[6], tupledata[7], tupledata[8], tupledata[9], '',
                               '0' if str(hellorbye) == '0' else tupledata[11],
                               tupledata[12], tupledata[13], waitingtime, '', '', tupledata[17],
                               tupledata[18], dbname)  # 557788
    print('----backcon---结束标志', backcon)
    return backcon


# 开启多线程
@time_statistic(2, 'cid')
def threaddefphone(text, cmpid, cid, sessionid, choiceback, location, channelid, serviceid, askid, operation,
                   industryid, wordslotid, session_data, session_sort, userid, dbname, originalcmpid, get_digits=None):
    # backtype1：文本2：列表3：连接4：附件5：图片 6：问题编码列表 7.回答问题并且推荐相关问题编码 8引导 9录音文件mp3 10录音文件wav
    # 回答类型回答类型1：匹配回答(问题库)2：列表3：无法回答4:寒暄5：调用接口（业务接口）6:表情包回答,7:机器人学习回答，8没有提供图片识别功能9：公司信息10:百度百科
    # 11:无法回答的问题，推荐问题库  12.匹配回答并返回相关问题 13.调用天气接口,14.引导提问 15.引导返回的答案 16.退出引导

    threadA = ThreadWithReturnValue(target=choiceanswerphoneA, args=(
        text, cmpid, cid, serviceid, sessionid, operation, askid, industryid, wordslotid, session_data, session_sort,
        userid, dbname, originalcmpid, get_digits))

    threadA.start()

    backA = threadA.join()
    if backA != None and type(backA) != str:
        return recordbackdataforquestion(len(backA), backA, sessionid, cid, operation, '', '', dbname)
    elif type(backA) == str:
        return backA
    else:
        no_match_cont = memcachcon.if_exist('notnextagain' + str(cid))
        if no_match_cont == None:
            no_match_cont = 0
        no_match = unknowphone(askid, cmpid, serviceid, operation, sessionid, cid,
                               no_match_cont, session_data, session_sort, userid, dbname)

        if no_match is None or len(no_match) != 0:

            return recordbackdataforquestion(4, no_match, sessionid, cid, operation, '', '', dbname)
        else:
            return endsentences(cmpid, serviceid, sessionid, cid, operation, '2', '2', session_data, session_sort,
                                userid, dbname)


# 未知问题
def unknowphone(askid, cmpid, serviceid, operation, sessionid, cid, num, session_data, session_sort, userid, dbname):
    no_match = selcommon(cmpid, serviceid, num, 'no_match', dbname, cid)

    if len(no_match) != 0:
        back = globalvariable(no_match[0][0], no_match[0][1], no_match[0][2], no_match[0][3], cid, cmpid, serviceid,
                              askid, 'no_match', '', no_match[0][4], no_match[0][5], no_match[0][6], session_data,
                              session_sort, userid, dbname)
        if back != None and len(back) != 0:
            return back


# 开启多线程
def threaddef(text, cmpid, cid, sessionid, choiceback, location, channelid, serviceid, dbname):
    # backtype1：文本2：列表3：连接4：附件5：图片 6：问题编码列表 7.回答问题并且推荐相关问题编码 8引导 9录音文件mp3 10录音文件wav
    # 回答类型回答类型1：匹配回答(问题库)2：列表3：无法回答4:寒暄5：调用接口（业务接口）6:表情包回答,7:机器人学习回答，8没有提供图片识别功能9：公司信息10:百度百科
    # 11:无法回答的问题，推荐问题库  12.匹配回答并返回相关问题 13.调用天气接口,14.引导提问 15.引导返回的答案 16.退出引导
    thread4 = ThreadWithReturnValue(target=choiceanswer4, args=(text, cmpid, channelid, dbname, cid))
    thread10 = ThreadWithReturnValue(target=choiceanswer10, args=(text, cmpid, dbname, cid))
    thread6 = ThreadWithReturnValue(target=choiceanswer6, args=(text, cmpid, dbname, cid))
    thread8 = ThreadWithReturnValue(target=choiceanswer8, args=(text, cmpid, dbname, cid))
    thread9 = ThreadWithReturnValue(target=choiceanswer9, args=(text, cmpid, dbname, cid))
    back13 = None
    if '天气' in text or choiceback == '13':
        thread13 = ThreadWithReturnValue(target=choiceanswer13, args=(text + str(location), cmpid))
        thread13.start()
        back13 = thread13.join()
    threadA = ThreadWithReturnValue(target=choiceanswerA, args=(text, cmpid, cid, serviceid, dbname))

    thread4.start()
    thread6.start()
    thread8.start()
    thread9.start()
    thread10.start()
    #
    threadA.start()

    # #获取返回值
    back4 = thread4.join()
    back6 = thread6.join()
    back8 = thread8.join()
    back9 = thread9.join()
    back10 = thread10.join()

    backA = threadA.join()
    if backA != None:

        return jugebackdata(len(backA), backA, sessionid, cid, dbname)
    elif back9 != None:
        return jugebackdata(len(back9), back9, sessionid, cid, dbname)
    elif back13 != None:
        return jugebackdata(len(back13), back13, sessionid, cid, dbname)
    else:
        if choiceback != '' and eval('back' + str(choiceback)) != None:
            return jugebackdata(len(eval('back' + str(choiceback))), eval('back' + str(choiceback)), sessionid, cid,
                                dbname)
        else:
            backall = ()
            if back4 != None:
                backall = backall + (back4,)
            if back6 != None:
                backall = backall + (back6,)
            if back8 != None:
                backall = backall + (back8,)
            if back10 != None:
                backall = backall + (back10,)
            if len(backall) != 0:
                backchoice = random.choice(backall)
                return jugebackdata(len(backchoice), backchoice, sessionid, cid, dbname)
            else:
                unknowtxt = random.sample(backtxt.backalltxt, 1)
                return jugebackdata(3, (unknowtxt[0], 1, 3), sessionid, cid, dbname)


# 访问机器人
def callrobotphone(cmpid, text, sessionid, cid, choiceback, location, channelid, serviceid, askid, operation,
                   industryid, wordslotid, session_data, session_sort, userid, dbname, originalcmpid, get_digits=None):
    # 判断是否启动引导

    return threaddefphone(text, cmpid, cid, sessionid, choiceback, location, channelid, serviceid, askid, operation,
                          industryid, wordslotid, session_data, session_sort, userid, dbname, originalcmpid, get_digits)


# 访问机器人
def callrobot1(cmpid, text, sessionid, cid, choiceback, location, channelid, serviceid, dbname):
    # 判断是否启动引导

    judgeopenguidance = jugeguidance(cmpid, text, cid, sessionid, dbname)
    if judgeopenguidance != "":
        return judgeopenguidance
    guidancedata = jugeguidancedata(cid, cmpid, text, sessionid, dbname)
    if guidancedata != '':
        return guidancedata

    data = jugeintention(text, cmpid, cid, '', sessionid, '', '', '', '', '', '', dbname)

    if data != None:
        # (backtext,backtype,1,'','open',askid,'','','',backtextremak,'','','','','')
        return backtypeadd(0, cid, data[1], data[0], '')
    return threaddef(text, cmpid, cid, sessionid, choiceback, location, channelid, serviceid, dbname)


# 查询表情库
def getmood(dbname, cid):
    sql = " select e.expression,e.expressionid from zy_rexpression e "
    mood = conn.mysql_sel(sql, dbname, cid)
    for i in mood:
        mongorobot.addmood(i[0], i[1])
    print('end')


# 查询无法回答的问题ignoretype 1:忽略的
def selunknowquestion(cmpid, begintime, endtime, pagesize, page, ignoretype, channerlid, serviceid, dbname, cid):
    sql = "select (select nickname from zt_cmp_robot  where onserviceid=cq.serviceid) as nickname,cq.contet," \
          "CAST(cq.Tdata as CHAR(100)) AS dtime,cq.cid, cq.sessionid,aw.ignoretype,cq.cmpid,cq.serviceid,cq.channerlid,aw.answerFlag " \
          "from zy_rcustomerquestion cq,zy_robotanswer aw where cq.cmpid='" + str(
              cmpid) + "' and aw.sessionid=cq.sessionid " \
        "    and aw.answerFlag=11 and  cq.contet!='' "
    if begintime != "" and endtime != "":
        sql += " and cq.Tdata BETWEEN '" + begintime + "' and '" + endtime + "'"
    elif begintime != "":
        sql += "and cq.Tdata>='" + begintime + "'"
    elif endtime != "":
        sql += "and cq.Tdata<='" + endtime + "'"
    if ignoretype != "":
        sql += " and aw.ignoretype='" + str(ignoretype) + "'"
    if channerlid != "":
        sql += " and cq.channerlid in (" + str(channerlid) + ")"
    if serviceid != "":
        sql += " and cq.serviceid='" + str(serviceid) + "'"

    sql += " GROUP BY cq.contet,cq.serviceid ORDER BY cq.Tdata DESC,aw.answerFlag DESC LIMIT " + str(
        int(pagesize) * (int(page) - 1)) + " , " + str(pagesize) + " "

    f = open('/usr/lzj/ChatterBotmaster_question/chatterbot/bigtxt/big.txt', 'r', encoding='utf-8')
    x = f.read().splitlines()
    a = 'attitude1'

    print("sql:{},dbname:{},cid:{}".format(sql, dbname, cid))
    unkonw = conn.mysql_seldic(sql, dbname, cid)
    # 肯定
    new_know = unkonw[:]

    for get_cid in new_know:
        for i in x:
            if a in i and get_cid['cid'] in i:
                unkonw.remove(get_cid)

    # unkonw = conn.mysql_seldic(sql,dbname,cid)
    return unkonw


# 查询无法回答的问题的数量
def selunknowquestioncount(cmpid, begintime, endtime, ignoretype, channerlid, serviceid, dbname, cid):
    sql = " select count(*) from  (  select cq.sessionid from zy_rcustomerquestion cq,zy_robotanswer aw \
     where cq.cmpid='" + str(cmpid) + "' and aw.sessionid=cq.sessionid      and aw.answerFlag=11 and  cq.contet!='' "
    if begintime != "" and endtime != "":
        sql += " and cq.Tdata BETWEEN '" + begintime + "' and '" + endtime + "'"
    elif begintime != "":
        sql += "and cq.Tdata='" + begintime + "'"
    elif endtime != "":
        sql += "and cq.Tdata='" + endtime + "'"
    if ignoretype != "":
        sql += " and aw.ignoretype='" + str(ignoretype) + "'"
    if channerlid != "":
        sql += " and cq.channerlid in (" + str(channerlid) + ")"
    if serviceid != "":
        sql += " and cq.serviceid='" + str(serviceid) + "'"
    sql += " GROUP BY cq.contet,cq.serviceid ORDER BY cq.Tdata DESC,aw.answerFlag DESC)a "
    unkonwcount = conn.mysql_selrowid(sql, dbname, cid)
    return unkonwcount


# 修改无法回答的问题忽略
def updataignore(sessionid, serviceid, cmpid, dbname, cid):
    sql = ""
    sure = 1
    sqlse = "select GROUP_CONCAT(r.sessionid) from zy_robotanswer a,zy_rcustomerquestion r " \
            "where r.contet=(select r.contet from zy_rcustomerquestion r where r.sessionid='" + str(sessionid) + "') " \
                                                                                                                 "and  r.sessionid = a.sessionid and r.cmpid='" + str(
                cmpid) + "'" \
        " and a.answerFlag=11 and a.ignoretype=0"
    if serviceid != "":
        sqlse += " and r.serviceid='" + str(serviceid) + "' "
    else:
        sqlse += " and r.serviceid is null "
    sessionidall = conn.mysql_selrowid(sqlse, dbname, cid)
    for id in sessionidall.split(','):
        sql = "UPDATE zy_robotanswer set ignoretype=1  where sessionid='" + str(id) + "' ;"
        sure = conn.mysql_updata(sql, dbname, cid)
    return sure


# 查询无法回答的问题的数量

# 返回json
def backunknow(code, backtype, backanswer):
    backtuple = {'code': str(code), 'backtype': str(backtype), 'backanswer': backanswer}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    return backcon


# 返回json数量，页数，当前页数
def backunknowpage(code, backtype, count, allpage, nowpage):
    backtuple = {'code': str(code), 'backtype': str(backtype), 'count': count, 'allpage': allpage, 'nowpage': nowpage}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    return backcon


# 根据问题编码获取答案
def fromquesidtoans(questionid, dbname, cid):
    sql = "select an.answer from zt_know_question q, zt_know_answer an where q.quesid=" + str(
        questionid) + " and q.answerid=an.answerid"
    back = conn.mysql_selrowid(sql, dbname, cid)
    return back


# 根据公司序号获取答案
def fromquestionnum(num, cmpid, dbname, cid):
    sql = "select a.answer from zt_know_question q,zt_know_answer a where q.cmpid=" + str(
        cmpid) + "  and q.sendno=" + str(num) + " \
         and a.answerid=q.answerid  "
    back = conn.mysql_selrowid(sql, dbname, cid)
    if back == "":
        back = "查询常见问题输入有误！"
    return back


# 添加公司简介
def addcompany():
    mongorobot.addcompany('公司名称', 'c1')
    mongorobot.addcompany('名称', 'c1')
    mongorobot.addcompany('你们公司叫什么', 'c1')
    mongorobot.addcompany('你们公司叫？', 'c1')
    mongorobot.addcompany('你是什么公司的啊', 'c1')
    mongorobot.addcompany('你们公司名称叫什么', 'c1')
    mongorobot.addcompany('你那边是哪里', 'c1')
    mongorobot.addcompany('公司的名称是什么', 'c1')
    mongorobot.addcompany('公司叫什么', 'c1')
    mongorobot.addcompany('公司邮箱', 'c2')
    mongorobot.addcompany('你们公司邮箱是什么呀', 'c2')
    mongorobot.addcompany('邮箱', 'c2')
    mongorobot.addcompany('你们公司的邮箱地址是什么', 'c2')
    mongorobot.addcompany('邮箱地址', 'c2')
    mongorobot.addcompany('公司邮箱是什么', 'c2')
    mongorobot.addcompany('你们邮箱是多少', 'c2')
    mongorobot.addcompany('你们公司邮箱是多少', 'c2')
    mongorobot.addcompany('可以把你们公司的邮箱发给我吗', 'c2')
    mongorobot.addcompany('公司传真', 'c3')
    mongorobot.addcompany('传真', 'c3')
    mongorobot.addcompany('你们公司的传真是多少', 'c3')
    mongorobot.addcompany('公司传真是什么', 'c3')
    mongorobot.addcompany('你们传真是多少啊 我传真过去吧', 'c3')
    mongorobot.addcompany('公司电话', 'c4')
    mongorobot.addcompany('你们的联系方式是', 'c4')
    mongorobot.addcompany('你们公司的联系方式是', 'c4')
    mongorobot.addcompany('电话', 'c4')
    mongorobot.addcompany('你们电话多少啊', 'c4')
    mongorobot.addcompany('你们公司电话是什么', 'c4')
    mongorobot.addcompany('电话号码发给我', 'c4')
    mongorobot.addcompany('电话号码是多少', 'c4')
    mongorobot.addcompany('服务热线', 'c4')
    mongorobot.addcompany('怎么联系你公司', 'c4')
    mongorobot.addcompany('公司地址', 'c5')
    mongorobot.addcompany('地址', 'c5')
    mongorobot.addcompany('你们公司在哪里', 'c5')
    mongorobot.addcompany('你们公司地址是', 'c5')
    mongorobot.addcompany('公司在哪？', 'c5')
    mongorobot.addcompany('在哪里', 'c5')
    mongorobot.addcompany('企业地址', 'c5')
    mongorobot.addcompany('你们地址在？', 'c5')
    mongorobot.addcompany('你们公司在什么地方啊', 'c5')
    mongorobot.addcompany('你们公司在哪？', 'c5')
    mongorobot.addcompany('你在哪呀', 'c5')
    mongorobot.addcompany('公司简介', 'c6')
    mongorobot.addcompany('公司描述', 'c6')
    mongorobot.addcompany('描述', 'c6')
    mongorobot.addcompany('简介', 'c6')
    mongorobot.addcompany('可以简单介绍一下们公司吗', 'c6')
    mongorobot.addcompany('你们公司是干嘛的呀', 'c6')
    mongorobot.addcompany('你们公司是做什么的呀', 'c6')
    mongorobot.addcompany('你是', 'c7')
    mongorobot.addcompany('你叫啥呀', 'c7')
    mongorobot.addcompany('你的名字是', 'c7')
    mongorobot.addcompany('你是谁', 'c7')
    mongorobot.addcompany('你叫什么', 'c7')
    mongorobot.addcompany('你是什么', 'c7')
    mongorobot.addcompany('你的名字叫什么', 'c7')
    mongorobot.addcompany('你是哪位啊', 'c7')
    mongorobot.addcompany('你是什么鬼啊', 'c7')
    mongorobot.addcompany('你好，你是哪位呀', 'c7')


# 多线程批量处理mongodb库
def thread_install_mongodbss(dbname):
    # 添加公司问题库
    mongodbthread_data = locals()
    allrb = haverobotincmp(dbname, '')
    for data in allrb:
        # print(data,dbname,'sdsds')
        mongodbthread_data[str(data[0]) + str(data[1])] = ThreadWithReturnValue(target=begin_install_mongodb,
                                                                                args=(data, dbname))
        mongodbthread_data[str(data[0]) + str(data[1])].start()
    for data in allrb:
        #  print(data)
        mongodbthread_data[str(data[0]) + str(data[1])].join()

    return '1'


# 执行插入到mongodb
def begin_install_mongodb(data, dbname):
    # mongodbcon.dropservice(str(dbname) + 'database' + str(data[0]))
    # 添加公司问题库
    allquestion = selinquestion(str(data[0]), str(data[1]), dbname, '')
    for que in allquestion:
        # print(data[0], que[0], que[1])
        if que != "":
            mongorobot.addstatement(str(data[0]), que[0], que[1], '', dbname)
        # 查询相似问题
        samedata = selasmequestion(que[2], dbname, '')
        for same in samedata:
            if same != "":
                mongorobot.addstatement(str(data[0]), same[0], que[1], '', dbname)
    # 添加机器人问题库
    allrb22 = haverobotincmpservice(data[0], dbname, '')
    for data1 in allrb22:
        # 服务问题库
        dataname = 'database' + str(data1[0]) + '-service' + str(data1[1])

        # print('dataname', dataname)
        allquestion = selinservicequestion(str(data1[0]), str(data1[1]), dbname, '')
        # 问题库
        # print('allquestion', allquestion)
        for que in allquestion:
            # print('que', que)
            mongorobot.addstatement(str(data1[0]), que[0], que[1], 'service' + str(data1[1]), dbname)
            # 查询相似问题
            samedata = selasmequestion(que[2], dbname, '')
            for same in samedata:
                if same != "":
                    mongorobot.addstatement(str(data1[0]), same[0], que[1], 'service' + str(data1[1]), dbname)
        # 添加机器人主流程态度
        allHoodleMobileid = selinHoodleMobileid(data1[0], data1[1], dbname, '')
        for HoodleMobileid in allHoodleMobileid:
            deldataname = 'database' + str(data1[0]) + '-HoodleMobile' + str(HoodleMobileid[0])
            worddata = selinatt(HoodleMobileid[0], dbname, '')
            for alldata in worddata:
                att = alldata[0]
                if alldata[1] == None:
                    pass
                else:
                    words = alldata[1].split(',')
                    for word in words:
                        # print(data1[0], HoodleMobileid[0], word, str(att))
                        if word != "":
                            mongorobot.addspecial(data1[0], HoodleMobileid[0], word, str(att), dbname)


# dbname_dict = {'127.0.0.1':'kefu10','localhost':'kefu10'}
# dbname_dict = {}
def get_dbname(ip, dbname):
    # global  dbname_dict
    # if ip in dbname_dict:
    return conn.basedbname
    #
